Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

To set (to 1) the particular bit:

regVal |= 1 << bitnum;

To reset (to 0) the particular bit:

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading