我有:
int8_t byteFlag;
我希望得到它的第一部分?我想我可能需要使用&
和>>
,但不确定具体如何。有什么帮助吗?
答案 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;
}