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

后端 未结 5 1870
臣服心动
臣服心动 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 18:19

    LSB is easy. Just x & 1.

    MSSB is a bit trickier, as bytes may not be 8 bits and sizeof(int) may not be 4, and there might be padding bits to the right.

    Also, with a signed integer, do you mean the sign bit of the MS value bit.

    If you mean the sign bit, life is easy. It's just x < 0

    If you mean the most significant value bit, to be completely portable.

     int answer  = 0;
     int rack = 1;
     int mask  = 1;
    
     while(rack < INT_MAX)
     {
        rack << = 1;
        mask << = 1;
        rack |= 1; 
     } 
    
     return x & mask;
    

    That's a long-winded way of doing it. In reality

    x & (1 << (sizeof(int) * CHAR_BIT) - 2); will be quite portable enough and your ints won't have padding bits.

提交回复
热议问题