有在Java没有二进制运算符可以直接与字节(8位)操作。类型为byte,short或char的变量在执行类似这些操作之前会自动将数字提升为32位整数,详见here。 因此,这里是你的代码会发生什么:
public static void main(String[] args) {
char hex[] = new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
byte b = (byte) 0xf1; // b is a byte with 0xf1
byte d = (byte)(b>>>4); // b is converted to int, becoming 0xfffffff1 then shifted
// to the right by 4 bits, resulting in 0x0fffffff
System.out.println("b>>>4=0x" + hex[(d>>4)&0x0f] + hex[d&0x0f]);
}
如果你想获得它只是更容易在下面的例子中使用32个变量对所有二进制运算,这样的权利:
public static void main(String[] args) {
char hex[] = new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
byte b = (byte) 0xf1;
int ib = b & 0xff;
byte d = (byte)(ib>>>4);
System.out.println("b>>>4=0x" + hex[(d>>4)&0x0f] + hex[d&0x0f]);
}
注意:如果您不知道,可以通过调用Integer.toHexString(n)
轻松打印十六进制格式的整数。