views:

783

answers:

6

Why byte b = (byte) 0xFF is equal to integer -1?

Ex:

int value = byte b = (byte) 0xFF;
System.out.println(value);

it will print -1?

+1  A: 

If you are using a signed int then 0xFF = -1 due to the 2-complement.

This wiki article explains it well, see the table on the right: http://en.wikipedia.org/wiki/Two%27s_complement

James Black
+1  A: 

Because Java (and most languages) represent negative integer values using two's-complement math. In two's-complement, 0xFF (11111111) represents (in a signed int) the value -1.

Michael Petrotta
+7  A: 

Bytes are signed in Java. In binary 0x00 is 0, 0x01 is 1 and so on but all 1s (ie 0xFF) is -1, oxFE is -2 and so on. See Two's complement, which is the binary encoding mechanism used.

cletus
And Java is doing sign extension when expanding the byte to an int. http://en.wikipedia.org/wiki/Two%27s_complement#Sign_extension
shf301
+4  A: 
  1. b is promoted to an int in determining which overload of system.out.println to call.

  2. All bytes in Java are signed.

  3. The signed byte 0xff represents the value -1. This is because Java uses two's complement to represent signed values. The signed byte 0xff represents -1 because its most significant bit is 1 (so therefore it represents a negative value) and its value is -128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1.

Jason
A: 

Its not just Java that does 2's complement math. That is the way every microprocessor and DSP that I can think of does math. So, its the way every programming language represents it.

SDGator
Strictly speaking, some languages (e.g. C and C++) do not specify what representation is used for integers. It is platform specific. on the other hand Java *does* specify 2's complement representation.
Stephen C
+2  A: 

perhaps your confusion comes from why (byte)0xFF is somehow equal to (int)0xFFFFFFFF. What's happening here is the promotion from smaller to larger signed types causes the smaller value to be sign extended, whereby the most significant bit is copied to all of the new bits of the promoted value. an unsigned type will not become sign-extended, they get zero extended, the new bits will always be zero.

If it helps you to swallow it, think of it this way, every integer of any size also has some 'phantom' bits that are too significant to be represented. they are there, just not stored in the variable. a negative number has those bits nonzero, and positive numbers have all zeros for phantom bits when you promote a smaller value to a larger one, those phantom bits become real bits.

TokenMacGuy