daedalus
daedalus

Reputation: 113

java, transfer first 3 bits from one byte to another in a single operation

I want to transfer the first 3 bits from one byte to another. Currently I use the following but its too slow (incorrect branch prediction slows things down)>

    byte newByte = 0;
    if(((oldByte >> 0)&1) == 1)  newByte |= 1 << 0;
    if(((oldByte >> 1)&1) == 1)  newByte |= 1 << 1;
    if(((oldByte >> 2)&1) == 1)  newByte |= 1 << 2;

How do I do this in a single operation without if statements or loops?

Note: other bits beyond bit num 3 may or may not be set in oldByte but I want to ignore them.

I tried using newByte |= oldByte but it transfers the set bits beyond bit num 3 which is not what I want.

any ideas?

Upvotes: 0

Views: 983

Answers (1)

Sam Estep
Sam Estep

Reputation: 13304

byte newByte = (byte) (oldByte & 0b111);

will do the trick. This works because 0b111 works as a mask, so only the rightmost three bits in oldByte will keep their original value after the calculation has been performed; the rest of the bits in oldByte will be set to 0. The result will then be assigned to newByte. You need to cast the result to a byte because the bitwise & operator produces an int, which is larger than a byte and so must be cast to convert properly.

If you want to get the first n bits from oldByte instead of the first 3 bits, you can do something like this:

byte newByte = (byte) (oldByte & ((1 << n) - 1));

Example when n == 3:

(1 << n) - 1
(1 << 3) - 1
0b1000 - 1
0b111

Upvotes: 6

Related Questions