问题
- 我想改变一些位的组合,而不影响其他位。
- 在这种组合中,一些位必须被取消设置或设置。
问题:什么是最好的掩码解决方案。特别是对于取消设置掩码。
例如:将bits[3:0] -> 0b1011 (data) 更改为 bits[3:0] -> 0b0110
让我分享一下我尝试过的方法:
- 创建了一个取消设置掩码:0b1001的取反 --> [1111]0110(将不关心的位更改为1)
- 创建了一个掩码:0b0110
有了这两个掩码,就可以使用按位操作了。
int data = 0xB; /*0b1011 (0xb) -> 0110 (0x6)*/
int umask = 0x9; /*unset mask 0b1001*/
int smask = 0x6; /*Set Mask 0b0110*/
data &= ~umask; /*Unset the bits what needs without affecting other*/
data |= smask; /*Set the bits what needs to be set*/
PORTB |= 1 << 2;
这样的一行代码将被转换为单个SBI
设置位的汇编指令。 - Nick T