Paul Gregoire
Paul Gregoire

Reputation: 9793

How to reverse a bit shifting method

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?

Upvotes: 1

Views: 3550

Answers (2)

cy3er
cy3er

Reputation: 1699

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

Upvotes: 1

Phylogenesis
Phylogenesis

Reputation: 7890

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

Upvotes: 1

Related Questions