Java 左移说明

Java left shift clarification

我无法找出此行为的原因。我想将字节值 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 的过程中,最左边的位用作符号位。

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

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

因为使用bitwise和byte时,short和char是先转成int再进行bitwise操作

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

在按位和 0xFF 之后,符号位被删除