Java 如何反转位移位法

Java 如何反转位移位法,java,bit-shift,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)); Sys

我有这个方法:

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; } 公共静态无效转储参数(字节b){ System.out.println(“参数:“+Integer.toHexString(b)); System.out.println(“参数1:+((b&0x01)>>0)); System.out.println(“参数2:+((b&0x02)>>1)); System.out.println(“参数3:+((b&0x0c)>>2)); System.out.println(“参数4:+((b&0xf0)>>4)); } 我试着用这种方法来扭转它:

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; } 公共静态字节设置参数(int b1、int b2、int b3、int b4){ 字节结果=(字节)b1; 结果|=(b2 | 0x02)这是我认为您正在尝试获取的代码:

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;
}
公共静态字节setParameters(int b1、int b2、int b3、int b4){
字节结果=(字节)b1;

结果|=(b2&0x01)按位or将完全破坏参数,只需将其移位,然后获取所需的位:

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;
}
公共静态字节setParameters(int b1、int b2、int b3、int b4){
字节结果=(字节)b1;

result |=(b2我认为您不想对常量使用
。尝试使用
result |=b2删除0x0c例如如何工作?dump方法对我的应用程序是有效的,这一点我是肯定的。因为
result |=(b3 | 0x0c)
按位ors
结果
与本例中的
52
相反。据我所知,您只是试图将2位设置在位置5和6。您的方法也可以工作,但@cy3er提交的方法“看起来”更接近原始的向前(转储)方法。