Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

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

1. ## 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.

```private static void convertByArray(long dV) {
int[] rem = new int;
int[] reverse = new int;
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....  Reply With Quote

3. ## 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

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

or in a clearer way
```int arrSize = (int)     ( (Math.log(dV)  /  Math.log(2) ) + 1);
int[] rem = new int[arrSize];```

after that you print out the array backwards:

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