Replace the least significant bit with bitwise operations

What is the best way to replace the least significant bit of a byte with the provided bit?

I know how to check and compare the last bit (using, for example, the posix ffs () function), but I want to know if there are solutions with better performance without checking if the replacement bit is 0 or 1.

The example is written in python as pseudocode, but I will implement a working algorithm in C:

>>> bin(0b1) # bit is '0b1' >>> bin(128) # byte is '0b10000000' >>> bin(129) # byte is '0b10000001' >>> bin(128 OPERATOR 0b1) # Replace LSB with 1 '0b10000001' >>> bin(128 OPERATOR 0b0) # Keep LSB at 0 '0b10000000' >>> bin(129 OPERATOR 0b1) # Keep LSB at 1 '0b10000001' >>> bin(129 OPERATOR 0b0) # Replace LSB with 0 '0b10000000' 

Obviously, an operator can be a set of operations, but I'm looking for an optimal (fast) method.

+7
source share
2 answers

n & ~1 replaces the least significant bit of n with zero; n | 1 n | 1 , with one.

To replace LSB with b , where b can be either 0 or 1, you can use (n & ~1) | b (n & ~1) | b .

To replace the k -th bit with b (where k=0 means LSB): (n & ~(1 << k)) | (b << k) (n & ~(1 << k)) | (b << k) .

+15
source

You may also need to check if you are in a architecture with a large entid or a small entium. On large-end machines, the least significant byte has the highest address.

In Python you can check endian-ness for

sys.byteorder

In C you need to authenticate yourself, hacking alliances is easy.

0
source

All Articles