如何反转位移方法

时间:2014-12-12 15:16:35

标签: java bit-shift

我有这个方法:

public static void dumpParameters(byte b) {
    System.out.println("Parameters: " + Integer.toHexString(b));
    System.out.println("Param 1: " + ((b & 0x01) >> 0));
    System.out.println("Param 2: " + ((b & 0x02) >> 1));
    System.out.println("Param 3: " + ((b & 0x0c) >> 2));
    System.out.println("Param 4: " + ((b & 0xf0) >> 4));
}

我试图用这种方法扭转它:

public static byte setParameters(int b1, int b2, int b3, int b4) {
    byte result = (byte) b1;
    result |= (b2 | 0x02) << 1;
    result |= (b3 | 0x0c) << 2;
    result |= (b4 | 0xf0) << 4;
    return result;
}

像这样调用这些方法:

dumpParameters((byte) 0xb2);
byte result = setParameters(0, 1, 0, 11);
dumpParameters(result);

结果:

Parameters: ffffffb2
Param 1: 0
Param 2: 1
Param 3: 0
Param 4: 11
Parameters: ffffffb6
Param 1: 0
Param 2: 1
Param 3: 1
Param 4: 11

我感兴趣的结果最终得到的值为 ffffffb6 ;我期待 ffffffb2

setParameters方法不起作用,为什么?

2 个答案:

答案 0 :(得分:1)

这是我想要获得的代码:

public static byte setParameters(int b1, int b2, int b3, int b4) {
    byte result = (byte) b1;
    result |= (b2 & 0x01) << 1;
    result |= (b3 & 0x03) << 2;
    result |= (b4 & 0x0f) << 4;
    return result;
}

答案 1 :(得分:1)

按位或将完全破坏参数,只需移动它们然后取所需的位:

public static byte setParameters(int b1, int b2, int b3, int b4) {
    byte result = (byte) b1;
    result |= (b2 << 1) & 0x02;
    result |= (b3 << 2) & 0x0c;
    result |= (b4 << 4) & 0xf0;
    return result;
}