Fran Pastor
Fran Pastor

Reputation: 53

Java conversion from 2 digists decimal into BCD in an int array

I have the necessity to convert a two digits decimal number into an int array. For instance, if we suppose that I have the number 32 i would like to convert it into int[] a = new int[2] where int[0] = 3 and int[1] = 2.

Upvotes: 1

Views: 1578

Answers (3)

Illyes Istvan
Illyes Istvan

Reputation: 579

A generalized version:

Suppose your number is stored in variable x.

final int x = 345421;
final String serialized = String.valueOf(x);
final int[] array = new int[serialized.length()];
for (int i = 0; i < serialized.length(); i++) {
    array[i] = Integer.valueOf(String.valueOf(serialized.charAt(i)));
}

Upvotes: 0

rp3220
rp3220

Reputation: 60

Try this:

int x, temp, i=0, j;
int[] a, b;
//Get the integer first and store in x 
//Also allocate the size of a and b with the number of digits that integer has
while(x > 0)
{
  temp = x%10;//gives remainder
  a[i] = temp;//store that value in array
  x = x/10;//to get the remaining digits
}
//the array will have the numbers from last digit

Ex:

i have x = 322

You will have the array a as { 2, 2, 3 }

 //to get the actual array try this
 j = a.length;
 while(i<j)
 {
    b[i]=a[j];
    i++;
    j--;
 }

You will have the array b as { 3, 2, 2 }

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You can try with:

int x = 32;
int[] array = { x / 10, x % 10 };

Upvotes: 1

Related Questions