Search code examples
cbit-manipulation

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

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);