0

So i've converted a float array and int array into binary number. The problem is when I print out the binary values, java cuts some of the digits off depending on how much the value is.

I've found this to be a problem with the int value because they don't start with 1 and it seems that java cuts all the leading 0's.

I want to show all 32-bits of the numbers so that I can format the numbers in columns...the columns come out staggered without the same amount of digits.

If you can think of a way around this problem I would appreciate it.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by masijade
0

toBinaryString only produces as many bits as is necessary to show the value. With negative numbers this should always be the complete amount as the leftmost digit is the "negative" indicator, but for positive numbers it is less. For example the number 10 will produce 1010 instead of 0000000000000000000000000000001010. You will need to "leftpad" the numbers yourself.

Here are two easy ways:

String base = "00000000000000000000000000000000";
String num = Integer.toBinaryString(10);
String complete = base.substring(0, 32 - num.length()) + num;
System.out.println(complete);
String complete2 = String.format("%32s", num).replace(' ', '0');
System.out.println(complete2);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.