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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With