6 Replies Latest reply: Feb 28, 2007 5:20 AM by 807606

# break up an int value

Hi,
I'm new here and this is my first post. I want to know if there is a way to break up an integer (like we can break a String using String.substring)?

The thing I'm trying to do is break up a long integer into 2-digit numbers (e.g. split 47393 into 93, 73, 4) and store them in a byte array with the first element of the byte array being the 2 least significant digits of the integer (e.g. 93 from 47393 goes into array[0] and 73 goes into array[1] and 4 goes into array[2]).

I need to perform arithmetic operations using these arrays but I'll try that myself later. Right now I'm stuck with the problem mentioned above. Can anyone help me please?
• ###### 1. Re: break up an int value
Convert it to a String, break it up, and convert the individual numbers back to ints when you store them in the array. It's a bit of overhead, but not eough to be worried about, unless you are doing it many thousands of times per second.
• ###### 2. Re: break up an int value
``````int toBreakUp = ...;
byte[] bytes = new byte[5]; // The maximum int is about 2^31
for(int i = 0; toBreakUp != 0; ++i){
bytes[i] = toBreakUp % 100;
toBreakUp = toBreakUp / 100;
}``````
• ###### 3. Re: break up an int value
I think, here is an additional cast necessary:
``toBreakUp = (byte)(toBreakUp / 100);``
• ###### 4. Re: break up an int value
Convert the integer value in to string, by using string.valueOf method
``````int number=152545;
String string=String.valueOf(number); ``````
Using stiring length., seperate the numbers.,
Then again Convert those String values in to integers., by using, integer.parseInt method,
``````String a="abc" ;
int b=Integer.parseInt(a);``````
Regards,
S.Vijay
• ###### 5. Re: break up an int value
Sorry, if have to correct myself once again (just for the correctness...)

Of course, the cast has to appear in the first assignment, so the complete code would be:
``````int toBreakUp = ...;
byte[] bytes = new byte[5]; // The maximum int is about 2^31
for(int i = 0; toBreakUp != 0; ++i){
bytes[i] = (byte)(toBreakUp % 100);
toBreakUp = toBreakUp / 100;
}``````
• ###### 6. Re: break up an int value
Thanks to all who replied. I think ProggerFromKupfer's code seems to do the job very well. Thanks again guys, I appreciate all your help.