检查C/C ++中的最低有效位(LSB)和最高有效位(MSB)的值 [英] Check value of least significant bit (LSB) and most significant bit (MSB) in C/C++
问题描述
我需要检查C/C ++中整数的最低有效位(LSB)和最高有效位(MSB)的值.我该怎么办?
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?
推荐答案
//int value;
int LSB = value & 1;
或者(从理论上讲不是可移植的,但实际上是-请参阅史蒂夫的评论)
//int value;
int LSB = value % 2;
详细信息: 第二个公式更简单. %运算符是余数运算符.一个数字的LSB为1(如果它是一个奇数),否则为0.因此,我们检查了除以2的余数.第一个公式的逻辑是:二进制数1是这个:
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
如果您将此二进制数与任意数字进行与"运算,则除最后一位外,结果的所有位都将为0,因为0 AND其他为0.如果最后一位,则结果的最后一位将为1.数字为1,因为1 & 1 == 1
和1 & 0 == 0
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.
这篇关于检查C/C ++中的最低有效位(LSB)和最高有效位(MSB)的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!