0

I am converting 4 integers into binary and everything works fine until it has to convert a zero.

for example:

int subnet1 = 255;
int subnet2 = 255;
int subnet3 = 255;
int subnet4 = 0;

binarystring = Integer.toBinaryString(subnet1) 
+ Integer.toBinaryString(subnet2)
+ Integer.toBinaryString(subnet3)
+ Integer.toBinaryString(subnet4);

BinaryView.setText(binarystring);

text would look like this: 11111111 11111111 11111111 0 (without the space inbetween)

why wont it convert the 0 to 00000000 ??

KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Bubuuh
  • 5
  • 4
  • Duplicate of [this](https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java) – Jon Goodwin Nov 30 '17 at 22:42

3 Answers3

0

Because value for "0000000" is same for "0" that's why it set as "0".

If you want to print that result. Just make a string of "0000000" for printing. Because int value always convert it.

KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Ankit Patidar
  • 2,731
  • 1
  • 14
  • 22
0

If you read the documentation here: https://developer.android.com/reference/java/lang/Integer.html#toBinaryString(int)

It tells you:

The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.

KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Why? By design. From the documentation:

This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.

(Emphasis added.)

If you want 8 characters, append the result to a string of 7 zeros, and take the last 8 characters. In pseudo code:

intermediateString = "0000000" + Integer.toBinaryString( 0 ); // obviously don't hard code zero; just for example
finalString = intermediateString.substring( intermediateString.length() - 8);
hunteke
  • 3,648
  • 1
  • 7
  • 17