如何读取unsigned int的特定位

我有一个uint8_t,我需要读/写特定的位。 我该怎么做呢? 具体来说,我的意思是我需要写入,然后再读取前7位为一个值,最后一位为另一个值。

编辑:忘了指定,我将这些设置为大端

你正在寻找bitmasking 。 学习如何使用C的按位运算符: ~|&^等将会有很大帮助,我建议你查阅它们。

否则 – 想要读掉最不重要的位?

 uint8_t i = 0x03; uint8_t j = i & 1; // j is now 1, since i is odd (LSB set) 

并设定它?

 uint8_t i = 0x02; uint8_t j = 0x01; i |= (j & 1); // get LSB only of j; i is now 0x03 

想要将i的七个最高有效位设置为j的七个最高有效位?

 uint8_t j = 24; // or whatever value uint8_t i = j & ~(1); // in other words, the inverse of 1, or all bits but 1 set 

想要读掉这些i?

 i & ~(1); 

想要读取i的第N个(从零开始索引,其中0是LSB)位?

 i & (1 << N); 

并设定它?

 i |= (1 << N); // or-equals; no effect if bit is already set 

当你学习C时,这些技巧会非常方便。