Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace least significant bit with bitwise operations

What is a optimal way to replace the Least Significant Bit of a byte, with a provided bit?

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

The example is written in python as pseudocode, but I will implement the 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 operator can be a set of operations, but I'm looking for the optimal (fastest) method.

like image 262
Emilio Avatar asked May 19 '11 13:05

Emilio


People also ask

How do you extract the least significant bit?

To be sure you get the right bit/value: The value at the least significant bit position = x & 1. The value of the isolated least significant 1 = x & -x. The zero-based index of the isolated least significant 1 = log2(x & -x)

How do you find the least significant bit of any number in C++?

int LSB = value & 1; for getting the least significant bit.

What is << in bit manipulation?

Left Shift ( << ): Left shift operator is a binary operator which shift the some number of bits, in the given bit pattern, to the left and append 0 at the end.

Which bit is LSB and MSB?

In a binary number, the bit furthest to the left is called the most significant bit (msb) and the bit furthest to the right is called the least significant bit (lsb). The MSB gives the sign of the number (sign bit) , 0 for positive and 1 for negative.


1 Answers

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

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

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

like image 76
NPE Avatar answered Oct 14 '22 14:10

NPE