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

后端 未结 5 1966
臣服心动
臣服心动 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:36

    Others have already mentioned:

    int LSB = value & 1;
    

    for getting the least significant bit. But there is a cheatier way to get the MSB than has been mentioned. If the value is a signed type already, just do:

    int MSB = value < 0;
    

    If it's an unsigned quantity, cast it to the signed type of the same size, e.g. if value was declared as unsigned, do:

    int MSB = (int)value < 0;
    

    Yes, officially, not portable, undefined behavior, whatever. But on every two's complement system and every compiler for them that I'm aware of, it happens to work; after all, the high bit is the sign bit, so if the signed form is negative, then the MSB is 1, if it's non-negative, the MSB is 0. So conveniently, a signed test for negative numbers is equivalent to retrieving the MSB.

提交回复
热议问题