C语言中的位掩码 - 如何获取字节的第一个比特?

6

我有:

int8_t byteFlag;

我想要获取它的第一位,我认为我可能需要使用&>>,但不确定具体该如何操作。有人能帮忙吗?


你所说的第一位是指最高位还是最低位? - asheeshr
我指的是最高有效位。 - Helen
5个回答

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

现在,func(byteFlag, 1)将会返回最低位中的第一位。您可以将whichBit设置为8以获取第八位(最高位)。

<<是左移运算符。它将把值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 << (whichBit-1)的作用?例如,如果whichBit是3,那么1 << 2是什么意思?我知道<<是左移。 - Helen
这个输出结果是否取决于处理器的字节序,还是始终为大端序? - sudo

3
你需要使用 & 运算符。
如果你所说的“第一个位”是指LSB:
int firstBit = byteFlag & 1;

如果您所说的“第一个比特”是指最高位(MSB):
int firstBit = byteFlag >> (sizeof(byteFlag) * 8 - 1);

1
从技术上讲,你只是得到了最后一位 :P - Jesus Ramos
int8_t 保证大小为1字节。 - Jesus Ramos
@Jesus:不,关于位数的编号有不同的约定。 - Paul R
@PaulR 我应该说至少为1个字节的大小。 - Jesus Ramos
谢谢!如果我想获取第三位比特,该怎么办?我不知道如何使用移位。 - Helen
1
@user1997839,听起来你只需要学习一些关于位移的知识:http://www.cprogramming.com/tutorial/bitwise_operators.html - itsme86

3

只需屏蔽高位即可。

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

由于这是有符号整数,因此另一个技巧是

if (byteFlag < 0) firstBitSet = true;

最后一个能工作是因为采用了二进制补码表示法。如果数字为负数,则高位被设置为1。

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

0
以下是解决方案。要获取数字的第一个位,将位设置为1;
int bitvalue(int8_t num, int bit)
{
    if (bit > 0 && bit <= 8)
        return ( (num >> (bit-1)) & 1 );
    else
        return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接