# How do I process an Arrays.toString in reverse order????

• March 4th, 2013, 09:45 PM
jessieaugust
How do I process an Arrays.toString in reverse order????
Here is my code for creating a decimal to binary converter that uses the remainders of a number entered divided by 2 to calculate the binary equivalent.

Code Java:

private static void convertByArray(long dV) {
int[] rem = new int[32];
int[] reverse = new int[32];
long maxVal = (long) (Math.pow(2,32) -1);
long nextVal;
if (dV > maxVal) {
System.out.println(
"Number too large for array method: max is: " + maxVal);

} else {
//convert by array method
int i = 0;
do {
nextVal = dV / 2;
rem[i] = (int) (dV % 2);
System.out.println("Decimal " + dV + " divided by 2 = "
+ nextVal + " with remainder of " + rem[i]);
dV = nextVal;
i++;
} while (dV > 0);
System.out.print("\nThe binary value of " + decVal + " is: ");

//process array in reverse order of calculation...

Arrays.sort(rem);
System.out.print(Arrays.toString(rem));

}
}

It produces the following output, which although correct, looks messy, and has to be read backwards (not good).

Decimal 2 divided by 2 = 1 with remainder of 0
Decimal 1 divided by 2 = 0 with remainder of 1

The binary value of 2 is: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

How can I reverse the order and eliminate the unnecessary zeros as well as the brackets so that if 2 is selected the binary value would be calculated simply as 10??????

Help....
• March 5th, 2013, 02:21 AM
janpiel
Re: How do I process an Arrays.toString in reverse order????
The easiest way is to use Long.toBinaryString but I think that's not the purpose of the thread;)
If you have a JDK you can also check the source of the toBinaryString-method there you can find a poser sophisticated way to solve it.

So:
To eliminate the zeros I recommend to limit the size of the array. So you must find out the count of digits of the binary number. That is the logarithm of base 2(for binary) to the input number plus 1

Code java:

int[] rem = new int[(int)((Math.log(dV) / Math.log(2)) + 1)];

or in a clearer way
Code java:

int arrSize = (int)     ( (Math.log(dV)  /  Math.log(2) ) + 1);
int[] rem = new int[arrSize];

after that you print out the array backwards:

Code java:

for (int j = rem.length - 1; j >= 0; j--) {
System.out.print(" " + rem[j] + " ");
}