Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit set/clear in C?

Tags:

c

embedded

How do I write to a single bit? I have a variable that is either a 1 or 0 and I want to write its value to a single bit in a 8-bit reg variable.

I know this will set a bit:

reg |= mask; // mask is (1 << pin)

And this will clear a bit:

reg &= ~mask; // mask is (1 << pin)

Is there a way for me to do this in one line of code, without having to determine if the value is high or low as the input?

like image 505
tylerjw Avatar asked Dec 08 '22 13:12

tylerjw


1 Answers

Assuming value is 0 or 1:

REG = (REG & ~(1 << pin)) | (value << pin);

I use REG instead of register because as @KerrekSB pointed out in OP comments, register is a C keyword.

The idea here is we compute a value of REG with the specified bit cleared and then depending on value we set the bit.

like image 138
ouah Avatar answered Dec 25 '22 08:12

ouah