你正在寻找bitmasking.学习如何用C的位运算符:~,|,&,^等将是巨大的帮助,我建议你看看他们.
否则 - 想要读掉最不重要的位?
uint8_t i = 0x03;
uint8_t j = i & 1; // j is now 1, since i is odd (LSB set)
Run Code Online (Sandbox Code Playgroud)
并设定它?
uint8_t i = 0x02;
uint8_t j = 0x01;
i |= (j & 1); // get LSB only of j; i is now 0x03
Run Code Online (Sandbox Code Playgroud)
想要将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
Run Code Online (Sandbox Code Playgroud)
想要读掉这些i?
i & ~(1);
Run Code Online (Sandbox Code Playgroud)
想要读取i的第N个(从零开始索引,其中0是LSB)位?
i & (1 << N);
Run Code Online (Sandbox Code Playgroud)
并设定它?
i |= (1 << N); // or-equals; no effect if bit is already set
Run Code Online (Sandbox Code Playgroud)
当你学习C时,这些技巧会非常方便.