简体   繁体   English

如何切换 8 位寄存器中的某些位?

[英]How can I toggle certain bits in an 8bit register?

Say I have bits 0-3 I want to toggle given a certain register value, how can I do that?假设我有位 0-3 我想在给定某个寄存器值的情况下切换,我该怎么做?

eg:例如:

unsigned char regVal = 0xB5; //1011 0101

// Toggle bits 0-3 (0101) to 1 without changing 4-7 where result should be 1011 1111

unsigned char result = regVal & (0x01 | 0x02 | 0x03 | 0x04);

or或者

unsigned char regVal = 0x6D; //0110 1101

// Toggle bits 4 and 7 to 1 without changing 1,2,3,5,6 where result should be 1111 1101

unsigned char result = regVal & (0x10 | 0x80);

The way I've attempted to mask above is wrong and I am not sure what operator to use to achieve this.我试图掩盖上面的方式是错误的,我不确定要使用什么运算符来实现这一点。

To set (to 1) the particular bit:设置(为 1)特定位:

regVal |= 1 << bitnum;

To reset (to 0) the particular bit:要重置(为 0)特定位:

regVal &= ~(1 << bitnum);

Te write the value to it (it can be zero or one) you need to zero it first and then set将值写入它(它可以是零或一)你需要先将它归零然后设置

regVal &= ~(1 << bitnum);
regVal |= (val << bitnum);
unsigned char regVal = 0xB5; //1011 0101
// Toggle bits 0-3 (0101) to 1 without changing 4-7 where result should be 1011 1111
regVal |= (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3);
unsigned char regVal = 0x6D; //0110 1101

// Toggle bits 4 and 7 to 1 without changing 1,2,3,5,6 where result should be 1111 1101

regVal |= (1 << 4) | (1 << 7);
unsigned char regVal = 0x6D; //0110 1101

// Set bits 4 to 7 to 1010 without changing 0, 1,2,3, 

regVal &= ~((1 << 4) | (1 << 5) | (1 << 6) | (1 << 7));
regVal |= (0 << 4) | (1 << 5) | (0 << 6) | (1 << 7);

Simply use bitwise XOR.只需使用按位异或。 regval ^= 0xFu; Or if you will regval ^= MASK;或者,如果你愿意regval ^= MASK;

And that's it.就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM