Search code examples
c++cintegerbit-manipulationbit

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?


Solution

  • //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.