Java左移澄清



我无法找出这种行为的原因。我想将字节值OxAB左移8位。然后我想把它转换成一个长。

byte oneByte = (byte) 0xAB;
long converted = (oneByte & 0xFF) << 8;
System.out.println(converted);

在这种情况下,输出为43776。但是,如果我将代码更改为:

byte oneByte = (byte) 0xAB;
long converted = (oneByte) << 8;
System.out.println(converted);

输出变为-21760。我有以下问题:

  1. 0xFF的数据类型是什么
  2. 为什么0xFF的位"与"会阻止符号扩展
long converted = onebyte; // gives you -85

如果你向左移动8次,它会精确地给出-21760因为在向长的转换期间,最左边的比特被用作符号比特。

long converted = onebyte & 0xFF; //gives you 171

如果你向左移动8次,就会得到43776

因为当使用按位和字节时,short和char会先转换为int,然后执行按位操作。

11111111111111111111111110101011 //byte 0xAB casted to int
00000000000000000000000011111111 //0xFF is an int literal
00000000000000000000000010101011 //bitwise and operation

在逐位和0xFF之后,符号位被去除

最新更新