2014-12-13 158 views
1

公共类UnsignedShift {位运算符

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; 
    byte d = (byte)(b>>>4); 


    System.out.println("b>>>4=0x" + hex[(d>>4)&0x0f] + hex[d&0x0f]); 

    } 

}

结果= 0xFF的

任何人都可以解释它是如何可能在Java中?

我认为,这是为0x0F

回答

1

有在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)轻松打印十六进制格式的整数。

0

字节B =(字节)的0xf1将1111 0001

字节d =(字节)(B >>> 4)将1111 1111

d >> 4将是11111111

为0x0F将00001111

(d >> 4)&为0x0F将00001111 == 15

d将是11111111

0F将是00001111

六角[d &为0x0F]将是00001111 == 15

所以最终的答案:0xFF的

我想你期待(字节)(B> >> 4)将0从左向右移动4次。但是b是一个32位的整数,它将从左边移动4个字节,但被(字节)转换忽略。字节转换占用整数的8个最低有效位。