简体   繁体   中英

JAVA: why binary literal for byte with negative sign is being considered as integer type?

I can't understand the following behavior.

I'm trying to declare byte mask using binary literal:

byte mask = 0b1111_1111;

But that's not possible, because I get the following error message:

Type mismatch: cannot convert from int to byte

The most interesting thing is that when I try to declare the mask directly, in decimal representation

byte mask = -1;

I get no error, but these two representations should be absolutely equal!

What am I doing wrong? Thanks in advance.

You can safely assign a values from -2^7 to 2^7-1 (-128 to 127) to a byte ,since it is 8 bits.

where as 0b1111_1111 = 255

So need a cast there

 byte mask = (byte) 0b1111_1111;

The value 0b1111_1111 is equal to 255, outside the byte 's range of [-128, 127] (because it is signed). Use:

byte mask=(byte)0b1111_1111&0xff;

The narrowing will remove the (all-zero) high bits and fit 8 into 8 without regard for sign.

Your "byte mask" is equivalent to 0xff or 255 , which are too large to fit in an 8-bit signed byte , not -1 , because the literal in the code is an int . If the value is within the range of a smaller type, the compiler can safely stuff it in there, but it can't safely assign a value outside the range -128..127 to a byte variable, and you'll need a cast.

除非另外投射或包含小数点或'e',否则所有数字文字都被视为'int'。

你可以这样做类型转换

    byte mask = (byte) 0b1111_1111;

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