C语言 C 中的位掩码 - 如何获取字节的第一位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14528233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bit masking in C - How to get first bit of a byte?
提问by Helen
I have:
我有:
int8_t byteFlag;
int8_t byteFlag;
and I want to get the first bit of it? I think I probably need to use &and >>but not sure how exactly. Any help?
我想得到它的第一点?我想我可能需要使用&,>>但不确定具体如何使用。有什么帮助吗?
回答by rashok
int func(int8_t byteFlag, int whichBit)
{
if (whichBit > 0 && whichBit <= 8)
return (byteFlag & (1<<(whichBit-1)));
else
return 0;
}
Now func(byteFlag, 1)will return 1'st bit from LSB. You can pass 8as whichBitto get 8th bit (MSB).
现在func(byteFlag, 1)将从 LSB 返回第一个位。您可以通过8aswhichBit获得第 8 位(MSB)。
<<is a left shift operant. It will shift the value 1to the appropriate place and then we have to do &operation to get value of that particual bit in byteFlag.
<<是左移操作数。它会将值移动1到适当的位置,然后我们必须进行&操作以获取byteFlag.
for func(75, 4)
为了 func(75, 4)
75 -> 0100 1011
1 -> 0000 0001
1 << (4-1) -> 0000 1000 //means 3 times shifting left
75 & (1 << (4 - 1))will give us 1.
75 & (1 << (4 - 1))会给我们1。
回答by itsme86
You would use the & operator.
您将使用 & 运算符。
If by "first bit" you mean LSB:
如果“第一位”是指 LSB:
int firstBit = byteFlag & 1;
If by "first bit" you mean MSB:
如果“第一位”是指 MSB:
int firstBit = byteFlag >> (sizeof(byteFlag) * 8 - 1);
回答by Jesus Ramos
Just mask the high bit
只屏蔽高位
int8_t high_bit = byteFlag & (1 << 7); //either 1 or 0
Another trick since this is a signed int
另一个技巧,因为这是一个有符号整数
if (byteFlag < 0) firstBitSet = true;
The last one works because of the representation of numbers in two's complement. The high bit is set if the number is negative.
最后一个工作是因为数字以二进制补码表示。如果数字为负,则设置高位。
回答by Anton Kovalenko
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. */
回答by Sudhir Sinha
The solution is given below. To get first bit of number, set bit = 1;
解决方法如下。要获取数字的第一位,请设置 bit = 1;
int bitvalue(int8_t num, int bit)
{
if (bit > 0 && bit <= 8)
return ( (num >> (bit-1)) & 1 );
else
return 0;
}

