简体   繁体   中英

Java byte value not correct

I have this hex value 93 which in decimal value should be 147. Since this number is less than 255, it is representable in a byte.

In java I did this

System.out.println((new Integer(1)).byteValue()); //prints 1
System.out.println((new Integer(147)).byteValue()); //prints -109!!! WHY?

What am I not understanding? with integer of 147 instead of printing 147 it prints -109...

A byte in Java is signed , therefore it represents the values in the range of -128 to 127, as opposed to the unsigned alternative in other languages in the range of 0 to 255. All of Java's integer types are signed, excluding char since since it's used to hold 16-bit Unicode values from 0 to 65535.

The value 147 stored as a byte is represented in binary as:

10010011

Since according to the Oracle docs a byte is: "an 8-bit signed two's complement integer" , the signed value becomes:

= -2^7 + 2^4 + 2^1 + 2^0
= -128 + 16 + 2 + 1
= -109

Because byte is in the range -128:127 ( see here ). When you call byteValue() you can't get anything out of that range, so it overflows (and starts from the lowest value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM