-1

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

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.

jabroni
  • 167
  • 16

2 Answers2

1

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);
0___________
  • 60,014
  • 4
  • 34
  • 74
  • I really wish C would just add binary constants, it would be so much easier to read than this. – puppydrum64 Jan 12 '23 at 11:45
  • @puppydrum64 gcc has it as an extension: https://godbolt.org/z/nf935TcKs – 0___________ Jan 12 '23 at 11:46
  • @puppydrum64 They will be added in the upcoming C23. Why, I don't know, since the correct solution is to use named constants for each mask, not magic numbers in any base. – Lundin Jan 12 '23 at 12:14
  • Honestly, I just find `0b10110011` easier to read than `(1 << 7) | (1 << 5) | (1 << 4) | (1 << 1) | 1` – puppydrum64 Jan 12 '23 at 15:07
0

Simply use bitwise XOR. regval ^= 0xFu; Or if you will regval ^= MASK;

And that's it.

Lundin
  • 195,001
  • 40
  • 254
  • 396