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?
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 inoldByte
will be set to 0. The result will then be assigned tonewByte
. You need to cast the result to abyte
because the bitwise & operator produces anint
, which is larger than abyte
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:
Example when
n == 3
: