1
votes

I have this method:

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

I tried to reverse it with this method:

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

Calling these methods like so:

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

Results:

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

The result I'm interested in ends up with a value of ffffffb6; I expected ffffffb2.

The setParameters method doesn't work, why?

2
I don't think you want to or against a constant. Try using result |= b2 << 1; etc. - Phylogenesis
How would dropping the 0x0c for instance work? The dump method is valid for my application, that much I'm certain of. - Paul Gregoire
Because result |= (b3 | 0x0c) bitwise-ors result against 52 in this instance. From what I can tell you're only trying to set the 2 bits at position 5 and 6. - Phylogenesis

2 Answers

1
votes

This is the code I think you're trying to get:

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
votes

The bitwise or will totally ruin the parameters, just shift them instead and then take the required bits:

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