how to set 3 lower bits of uint8_t in C

9.9k views Asked by At

I would like to set the 3 lower bites of uint8_t with value 3. I've tried the following:

uint8_t temp = some_value;
temp = temp & 0x3

but this does not work....

4

There are 4 answers

5
Lee Daniel Crocker On BEST ANSWER

To set bits you need |:

temp = temp | 0x3;

or more compactly:

temp |= 0x3;

If you want to set a 3-bit span to the number 3, you need to both set and clear bits:

temp &= ~0x7; // clear bits
temp |= 0x3;  // set bits
0
Sami Kuhmonen On

& 3 is logical and, it will clear all bits except two lowest. You want to or also.

So to set three lowest bits to three, you would use temp = (temp & ~7) | 3. ~ is a logical not, which turns 7 into "all other bits than the last three", which when used with and will clear the three bits. After that or the 3 into it.

2
David Grayson On

This will change the 3 lower bits of z to 011 (3), while preserving the upper 5 bits:

uint8_t z = something();
z = (z & ~7) | 3;

After this, the bits of z will look like this, where x means "unknown":

xxxxx011
0
Havenard On

To set the three lower bits you need to set the mask 0x07, because 7 represented in binary is 00000111.

If you want to get a mask of lower bits by specifying the number of bits, you can use this formula:

int bits = 3; // 3 lower bits
uint8_t mask = (1 << bits) - 1; // 7

To clear the pre-existing value of those bits, use a negative of the mask with the bitwise operator "and":

temp = temp & ~mask; //  mask is 00000111
                     // ~mask is 11111000 (negative)
                     // this operation zero out the 3 last bits of temp

And then you assign a new value to those bits with the bitwise operator "or":

temp = temp | (new_value & mask); // applying mask to new_value to make
                                  // sure its within the bit limit