pls help in understanding the range of byte

Printable View

• 06-23-2010, 10:49 PM
shivamskn
pls help in understanding the range of byte
the range of byte according to book is -128 to 127. The binary representation of -128 is 110,000,000 which is 9 bits so how it can be stored in a byte. When I convert -128 to its binary form and print it to console the output is 10,000,000 that is 0x80 in hex. But the compiler gives an error when I execute the following statement byte b=0x80. The error it gives is possible loss of precision. Pls help am confused.:confused:
• 06-24-2010, 12:37 AM
pbrockway2
You say that the binary representation of -128 is 110 000 000, but I imagine there are lots of binary representations of numbers.

The JLS describes bytes as 8 bit signed two's-complement integers. The JLS link is perhaps not so useful at this stage, but you will probably want to check out the details of two's complement. (Eg at Wikipedia). According to the table on that page the representation of -128 is 10 000 000 which is exactly what you saw when you used System.out.print*().

That you got a complaint from the compiler when you said "byte b = 0x80" is no surprise: after all you said the range of byte is [-128,127] and 0x80 is 128. The same bit pattern may well be used for the byte value of negative 128, but the compiler will treat "0x80" as an integer with a value of 128 and that's too big.
• 06-24-2010, 12:07 PM
shivamskn
thanks......understood it from ur wiki link