Question

I'm attempting to learn how to program micro-controllers in C and have a question regarding bit assignments. Say for example I were to declare an 8 bit number.

binary_number = 0b00000000;

Now, lets say I wanted to set bit 3 only. Example texts I have seen use an operation like the following:

binary_number |= (1<<4)

Am I understanding this correctly? We are taking binary_number and 'or-ing' it with essentially 0b00001000 and then assigning that outcome to binary_number?

Likewise, when resetting this bit:

binary_number &= ~(1<<4)

We are essentially taking binary_number (0b00001000) and 'and-ing' it with 0b11110111 and then assigning binary_number to the outcome of that expression?

Do I understand this correctly?

Was it helpful?

Solution

Yes, your understanding is correct! :) but a little change...

For resetting or setting the bit 3, you need to left shift the 1 by 3 places only.
1<<4 : 0b00010000
1<<3 : 0b00001000

Use the bitwise OR operator (|) to set xth bit.

n |= 1 << x;

That will set bit x.

Use the bitwise AND operator (&) to reset xth bit.

n &= ~(1 << x);

That will reset bit x.

OTHER TIPS

Yes, you are understanding it correctly. That is exactly what you have to do to set and unset bits. Looks pretty complicated I know but you could always write a helper function that you pack around with you.

As pointed out others, you are setting/resetting the 4th bit not the 3rd

Set mask:     1<<4 =    10000 = 0001 0000
Reset Mask: ~(1<<4) = ~(10000)= ~(0001 0000) = 1110 1111

So, binary_number |= (1<<4):

Original Number     -      0000 0000
Mask to set 4th bit - (OR) 0001 0000
                           --------
Result                     0001 0000 //4th bit set

And, binary_number &= ~(1<<4):

Original Number     -       000X 0000 //4th bit could be a 1 or a 0; X =1/0
Mask to set 3rd bit - (AND) 1110 1111
                            --------
Result                      0000 0000 //4th bit reset

If you seek efficiency the best way to do it is to define the bits individually:

#define BIT_0  0b00000001
#define BIT_1  0b00000010
#define BIT_2  0b00000100
#define BIT_3  0b00001000
#define BIT_4  0b00010000
#define BIT_5  0b00100000
#define BIT_6  0b01000000
#define BIT_7  0b10000000

and then to set the bit in a byte:

unsigned char byteWhoseBitsAreSetReset = 0;

//To Set bit 3
byteWhoseBitsAreSetReset |= BIT_3;

//To Set Multiple bits
byteWhoseBitsAreSetReset |= (BIT_3 + BIT_4 + BIT_5);
//OR
byteWhoseBitsAreSetReset |= (BIT_3 | BIT_4 | BIT_5);

//To reset bit 3
byteWhoseBitsAreSetReset &= ~(BIT_3);

//To reset Multiple bits
byteWhoseBitsAreSetReset &= ~(BIT_3 + BIT_4 + BIT_5);
//OR
byteWhoseBitsAreSetReset &= ~(BIT_3 | BIT_4 | BIT_5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top