0

I have the following code:

    int i =128;
    byte b = (byte) i;
    System.out.println( Integer.toBinaryString(i)); //10000000
    System.out.println( Integer.toBinaryString(b)); //11111111111111111111111110000000

could someone explain why 1's were added to the left when casting from Integer to Byte and how could a byte carry more than 8 bits !?

Assem-Hafez
  • 1,045
  • 10
  • 11

1 Answers1

1

You are calling .toBinaryString on the Integer class, so your number is treated as an Integer in any case.

The reason the second call has so many 1 is because it is a negative number. In Java, bytes are signed, so the maximum positive value is 127. By casting 128 into a byte you are actually representing -128. When you cast that small negative number into an 32 bit signed integer as you were doing, all those 1s appear at the beginning.

jjmontes
  • 24,679
  • 4
  • 39
  • 51