Java binary literals - Value -128 for byte

流过昼夜 提交于 2019-11-29 10:28:42

According to the Java Specification,

http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1

all your declarations (b, b1,..., and b8) use int literals, even when they would fit in a byte. There's no byte literal in Java, you can only use an int to initialize a byte.

I did some tests and byte neg128 = -0b1000_0000; works fine. 0b1000_0000 is 128, so you just need to put a - sign before it. Notice that that 1 is not a sign bit at all (don't think about 8-bit bytes, think about 32-bit ints converted to bytes). So if you want to specify the sign bit you need to write all 32 bits, as you have demonstrated.

So byte b8 = 0b1000_0000; is an error just like byte b8 = 128; is an error (+128 does not fit in a byte). You can also force the conversion with a cast:

byte b = (byte) 0b1000_0000; or byte b = (byte) 128;

The cast tells the compiler that you know 128 does not fit in a byte and the bit-pattern will be reinterpreted as -128.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!