C中的位掩码 - 如何获取字节的第一位?

时间:2013-01-25 18:37:54

标签: c byte bit-manipulation bit

我有:

int8_t byteFlag;

我希望得到它的第一部分?我想我可能需要使用&>>,但不确定具体如何。有什么帮助吗?

5 个答案:

答案 0 :(得分:9)

int func(int8_t byteFlag, int whichBit)
{
    if (whichBit > 0 && whichBit <= 8)
        return (byteFlag & (1<<(whichBit-1)));
    else
        return 0;
}

现在func(byteFlag, 1)将从LSB返回第1位。您可以将8作为whichBit传递到第8位(MSB)。

<<是左移操作员。它会将值1转移到适当的位置,然后我们必须执行&操作以获取byteFlag中该特定位的值。

代表func(75, 4)

75         -> 0100 1011
1          -> 0000 0001
1 << (4-1) -> 0000 1000 //means 3 times shifting left

75 & (1 << (4 - 1))会给我们1

答案 1 :(得分:3)

你会使用&amp;操作

如果用“第一位”表示LSB:

int firstBit = byteFlag & 1;

如果用“第一位”表示MSB:

int firstBit = byteFlag >> (sizeof(byteFlag) * 8 - 1);

答案 2 :(得分:3)

掩盖高位

int8_t high_bit = byteFlag & (1 << 7); //either 1 or 0

因为这是一个签名的int

的另一个技巧
if (byteFlag < 0) firstBitSet = true;

最后一个是有效的,因为数字以二进制补码表示。如果数字为负,则设置高位。

答案 3 :(得分:0)

int8_t bit_value = (byteFlag & (1U << bitPosition)) ? 1 : 0 ;
/* now it's up to you to decide which bit is the "first".
   bitPosition = 0 is the minor bit. */

答案 4 :(得分:0)

解决方案如下。要获得第一位数,请设置bit = 1;

int bitvalue(int8_t num, int bit)
{
    if (bit > 0 && bit <= 8)
        return ( (num >> (bit-1)) & 1 );
    else
        return 0;
}