简体   繁体   中英

Java Bitshift Operation: error converting int to byte

can someone tell me why the following code is throwing the compile error "cannot convert from int to byte"?

byte x = 2;  
byte y = (x >> 1);

I mean I clearly declared both x and y as bytes, and 'x >> 1' will evaluate to 1 ie still be in the range of a byte.
Also when I do something like

byte x = -2;  
System.out.println(x >>> 1);

I would expect 126 to be the outcome, because I shifted a 0 in the leftmost bit of b1111 1101 , which is 0111 1110 . But the console is printing ' 2147483647 ', so it looks like my byte has been converted to an integer before the 0 has been shifted in. Why is that? Please help me out.

Simply because x >> 1 returns an int so you simply need to cast it explicitly to a byte as next:

byte y = (byte)(x >> 1);

Please also note that since it is an int operator (or long depending on the left-hand operant cf §15.19 from the specification), all its operands must be of type int which means that in your case x will be implicitly converted into an int too in other words x >> 1 is equivalent to (int)x >> 1

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