Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check value of least significant bit (LSB) and most significant bit (MSB) in C/C++

I need to check the value of the least significant bit (LSB) and most significant bit (MSB) of an integer in C/C++. How would I do this?

like image 485
delaccount992 Avatar asked Jul 11 '11 08:07

delaccount992


People also ask

How do you find most significant bit and least significant bit?

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.

What is MSB in C?

The most significant bit (MSB) is the bit in a multiple-bit binary number with the largest value. This is usually the bit farthest to the left, or the bit transmitted first in a sequence. For example, in the binary number 1000, the MSB is 1, and in the binary number 0111, the MSB is 0.

How do you find the least significant bit?

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)


Video Answer


1 Answers

//int value; int LSB = value & 1; 

Alternatively (which is not theoretically portable, but practically it is - see Steve's comment)

//int value; int LSB = value % 2; 

Details: The second formula is simpler. The % operator is the remainder operator. A number's LSB is 1 iff it is an odd number and 0 otherwise. So we check the remainder of dividing with 2. The logic of the first formula is this: number 1 in binary is this:

0000...0001 

If you binary-AND this with an arbitrary number, all the bits of the result will be 0 except the last one because 0 AND anything else is 0. The last bit of the result will be 1 iff the last bit of your number was 1 because 1 & 1 == 1 and 1 & 0 == 0

This is a good tutorial for bitwise operations.

HTH.

like image 84
Armen Tsirunyan Avatar answered Oct 17 '22 05:10

Armen Tsirunyan