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
?
Bytes are signed in Java. In binary 0x00 is 0, 0x01 is 1 and so on but all 1s (ie 0xFF) is -1, 0xFE is -2 and so on. See Two's complement, which is the binary encoding mechanism used.
b
is promoted to anint
in determining which overload ofsystem.out.println
to call.All bytes in Java are signed.
The signed byte
0xff
represents the value-1
. This is because Java uses two's complement to represent signed values. The signed byte0xff
represents-1
because its most significant bit is1
(so therefore it represents a negative value) and its value is-128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1
.
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.
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
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.
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.
reduced modulo
byte = 256 0xff = 255
255 / 256 -> remainder 255
So 255 - 256 = -1
Simple Logic Cheers
来源:https://stackoverflow.com/questions/1677957/why-byte-b-byte-0xff-is-equals-to-integer-1