2

So, i'm fairly new to java, and i'm a bit confused about the byte system. So I made this program that converts integers to their base two value.

class Bits
{
    public static void main(String[] args)
    {
        byte a;
        a = 5;
        System.out.println(Integer.toBinaryString(a)); /* prints 101 */
        a = -1;
        System.out.println(Integer.toBinaryString(a)); /* prints
        11111111111111111111111111111111*/
    }
}

It works as expected with positive numbers, but when I enter negative numbers, it gets weird. Now I know what two's compliment is, and it doesn't say that -1 is 11111111111111111111111111111111. It is supposed to be 11111111, right? When I change a to an int 255, which would be -1 as a byte, I get the normal result, 11111111, when I switch it to binary. Can someone explain to me why this is happening, or did I do something wrong. (I am using java 8 and i'm on a mac)

Jack
  • 131,802
  • 30
  • 241
  • 343
Vityou
  • 152
  • 1
  • 11

1 Answers1

1

Integer.toBinaryString accepts an int as an argument. So a is casted from byte to int before being passed to the method. And yes the two's complement of -1 of a 32 bits integer is 11111111111111111111111111111111.

You should try with Integer.toBinaryString(a & 0xFF). So that a is widened to 32 bits, but then 24 most relevant bits are discarded through masking. The bit sign is kept since you were starting from a byte so the result will be correct.

You can verify it by converting the truncating the int converted from a and the parse it as an int and converting it back to a byte:

int counter = 0;
for (byte a = -128; counter <= 256; ++a, ++counter)
{
   byte b = (byte)(Integer.valueOf(Integer.toBinaryString(a & 0xFF), 2) & 0xFF);
   System.out.println(a+" == "+b);
}
Jack
  • 131,802
  • 30
  • 241
  • 343