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

后端 未结 5 1878
臣服心动
臣服心动 2021-01-31 18:02

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?

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 18:35

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

提交回复
热议问题