我有:
int8_t byteFlag;
我想要获取它的第一位,我认为我可能需要使用&
和>>
,但不确定具体该如何操作。有人能帮忙吗?
我有:
int8_t byteFlag;
我想要获取它的第一位,我认为我可能需要使用&
和>>
,但不确定具体该如何操作。有人能帮忙吗?
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
。
int firstBit = byteFlag & 1;
int firstBit = byteFlag >> (sizeof(byteFlag) * 8 - 1);
int8_t
保证大小为1字节。 - Jesus Ramos只需屏蔽高位即可。
int8_t high_bit = byteFlag & (1 << 7); //either 1 or 0
由于这是有符号整数,因此另一个技巧是
if (byteFlag < 0) firstBitSet = true;
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. */
int bitvalue(int8_t num, int bit)
{
if (bit > 0 && bit <= 8)
return ( (num >> (bit-1)) & 1 );
else
return 0;
}