如何添加和提取位到一个字节?

How to add and extract bits to a byte?

我正在尝试理解 bitbyte manipulation,我在 SO 中看到了很多例子。不过,我对自己的理解还有一些疑问。

首先,假设我们有一个字节顺序为 Least Significant Bytebyte array。我想从这个数组中获取字节 2。我可以得到像 byte[1] 这样的字节。我说得对吗?

其次,我们有一个byte array,字节顺序为Least Significant Byte。我想获得字节 1! 的前 2 位。如何从该字节中获取前 2 位? 另外,如何将一个数字添加到一个字节的前 2 位?

非常感谢任何帮助或link理解这些逻辑。

First, lets say we have a byte array with the byte order as LSB. I want to get the byte 2 from this array. I can get the byte like byte[1]. Am I right?

是的。

Second, we have a byte array with the byte order as LSB. And I want to get first 2 bits of the byte 1!. How can I get the first 2 bits from that byte? Also, how can I add a number into the first 2 bits of a byte?

您可以使用按位与运算符 & 和常量 3 来仅检索前两位。通过num & 3实现num3的每个位之间的条件运算,只有当两个位都为1时才返回1作为结果位。因为3只有它的2设置第一位后,num 中除前 2 位以外的所有位都将被忽略。

unsigned char foo = 47;
unsigned char twobits = foo & 3; // this will return only the value of the two bits of foo.
unsigned char number_to_add = 78;
twobits &= (number_to_add & 3); // this will get the values of the 2 bits of number_to_add_ and then assign it to the 2 bits of variable twobits.

或者,如果您不关心 endianess,您可以使用位域:

struct st_foo
{
     unsigned char bit1 : 1;
     unsigned char bit2 : 1;
     unsigned char the_rest : 6;
};

struct st_foo my_byte;
my_byte.bit1 = 1;
my_byte.bit2 = 0;