如何在C中设置uint8_t的3个低位

Ale*_*x L 1 c bitwise-operators

我想将 uint8_t 的 3 个下位设置为值 3。我尝试了以下操作:

uint8_t temp = some_value;
temp = temp & 0x3
Run Code Online (Sandbox Code Playgroud)

但这不起作用......

Lee*_*ker 5

要设置您需要的位|

temp = temp | 0x3;
Run Code Online (Sandbox Code Playgroud)

或者更紧凑:

temp |= 0x3;
Run Code Online (Sandbox Code Playgroud)

如果要将 3 位跨度设置为数字 3,则需要设置和清除位:

temp &= ~0x7; // clear bits
temp |= 0x3;  // set bits
Run Code Online (Sandbox Code Playgroud)

  • @Bear 听起来你忘记取消引用你的指针。应该是 *temp = *temp | 0x3; (2认同)