如何在 C 中设置 uint8_t 的低 3 位
how to set 3 lower bits of uint8_t in C
我想将 uint8_t 的 3 个低位设置为值 3。
我试过以下方法:
uint8_t temp = some_value;
temp = temp & 0x3
但这不起作用....
& 3
是合乎逻辑的,它将清除除最低两位以外的所有位。你要还是也。
所以要将三个最低位设置为三,您可以使用 temp = (temp & ~7) | 3
。 ~ 是一个逻辑非,它将 7 变成 "all other bits than the last three",当与 and 一起使用时将清除这三个位。之后还是3进吧。
要设置您需要的位 |
:
temp = temp | 0x3;
或更紧凑:
temp |= 0x3;
如果要将 3 位跨度设置为数字 3,则需要同时设置和清除位:
temp &= ~0x7; // clear bits
temp |= 0x3; // set bits
这会将 z
的低 3 位更改为 011
(3),同时保留高 5 位:
uint8_t z = something();
z = (z & ~7) | 3;
在此之后,z
的位将如下所示,其中 x
表示 "unknown":
xxxxx011
要设置低三位你需要设置掩码0x07
,因为7用二进制表示是00000111
.
如果想通过指定位数得到低位掩码,可以使用这个公式:
int bits = 3; // 3 lower bits
uint8_t mask = (1 << bits) - 1; // 7
要清除这些位的预先存在的值,请将掩码的负数与按位运算符一起使用 "and":
temp = temp & ~mask; // mask is 00000111
// ~mask is 11111000 (negative)
// this operation zero out the 3 last bits of temp
然后使用按位运算符 "or":
为这些位分配一个新值
temp = temp | (new_value & mask); // applying mask to new_value to make
// sure its within the bit limit
我想将 uint8_t 的 3 个低位设置为值 3。 我试过以下方法:
uint8_t temp = some_value;
temp = temp & 0x3
但这不起作用....
& 3
是合乎逻辑的,它将清除除最低两位以外的所有位。你要还是也。
所以要将三个最低位设置为三,您可以使用 temp = (temp & ~7) | 3
。 ~ 是一个逻辑非,它将 7 变成 "all other bits than the last three",当与 and 一起使用时将清除这三个位。之后还是3进吧。
要设置您需要的位 |
:
temp = temp | 0x3;
或更紧凑:
temp |= 0x3;
如果要将 3 位跨度设置为数字 3,则需要同时设置和清除位:
temp &= ~0x7; // clear bits
temp |= 0x3; // set bits
这会将 z
的低 3 位更改为 011
(3),同时保留高 5 位:
uint8_t z = something();
z = (z & ~7) | 3;
在此之后,z
的位将如下所示,其中 x
表示 "unknown":
xxxxx011
要设置低三位你需要设置掩码0x07
,因为7用二进制表示是00000111
.
如果想通过指定位数得到低位掩码,可以使用这个公式:
int bits = 3; // 3 lower bits
uint8_t mask = (1 << bits) - 1; // 7
要清除这些位的预先存在的值,请将掩码的负数与按位运算符一起使用 "and":
temp = temp & ~mask; // mask is 00000111
// ~mask is 11111000 (negative)
// this operation zero out the 3 last bits of temp
然后使用按位运算符 "or":
为这些位分配一个新值temp = temp | (new_value & mask); // applying mask to new_value to make
// sure its within the bit limit