Alex L
Alex L

Reputation: 1089

how to set 3 lower bits of uint8_t in C

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....

Upvotes: 1

Views: 10805

Answers (4)

Havenard
Havenard

Reputation: 27894

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

Upvotes: 3

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31173

& 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.

Upvotes: 2

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

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

Upvotes: 5

David Grayson
David Grayson

Reputation: 87466

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

Upvotes: 1

Related Questions