Java 位运算符

Java 位运算符,java,binary,bit-manipulation,shift,Java,Binary,Bit Manipulation,Shift,公共类无符号移位{ 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>>&g

公共类无符号移位{

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

在java中没有可以直接使用字节(8位)操作的二进制运算符。byte、short或char类型的变量在执行类似操作之前会自动“数字升级”为32位整数,如中所述。 下面是代码中发生的情况:

如果您想正确实现这一点,那么在所有二进制操作中使用32位变量就更容易了,如下例所示:

注意:如果您不知道,您可以通过调用
integer.toHexString(n)
以十六进制格式轻松打印整数

字节b=(字节)0xf1将是1111 0001

字节d=(字节)(b>>>4)将是1111111

d> >4将是11111

0x0f将是00001111

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

d将是11111

0f将是00001111

十六进制[d&0x0f]将为00001111==15

最后的答案是:0xff

我认为您期望(字节)(b>>>4)将0从左向右移动4次。但b是一个32位的整数,它将从左移4个字节,但被(字节)转换忽略。字节转换采用整数的8个最低有效位

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]);

}
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]);
}