I am working on a function that receives a byte and needs to change some of the bits in that byte.
For example, the function receives:
11001011
Then I need to set the MSB to 0, its easy enough:
buffer[0] &= ~(1 << 7);
But then I need to set bits 6 through 3 (I refer LSB as bit 0 here) to an argument that gets supplied to the function. This argument can be an integer from 0 to 6.
The important thing is I should not change any other bits.
I tried with masking and stuff but I failed miserably. Then as last resort I did it painfully like below. It works fine...but it is ugly and generates tons of instructions, making the code run slow:
switch(regAddress) {
case 0:
buffer[0] &= ~(1 << 5);
buffer[0] &= ~(1 << 4);
buffer[0] &= ~(1 << 3);
break;
case 1:
buffer[0] &= ~(1 << 5);
buffer[0] &= ~(1 << 4);
buffer[0] |= (1 << 3);
break;
//YOU GOT THE IDEA!!.....
}
Please let me know hot to do this in one (or two) line of code so I can learn the trick.
I did a mistake, the argument passed is alway 0 to 6, so the MSB of the 4bits that I want to set is always zero, therefore before the switch case I did like:
//because we only have 7 address, we already set the 4th bit to 0
buffer[0] &= ~(1 << 6);