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....
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....
& 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.
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
To set bits you need
|
:or more compactly:
If you want to set a 3-bit span to the number 3, you need to both set and clear bits: