Page 1 of 1

change individual bits in a byte

Posted: Thu Nov 23, 2023 5:11 pm
by DirkB
Hello,

How can I change individual bits in a byte?

Thank you
Dirk

Re: change individual bits in a byte

Posted: Thu Nov 23, 2023 5:44 pm
by mnfisher
You use | (or) and & (and)

For example

.v = .v | (1 << 5) will set bit 5 in .v
.v = .v & ~(1 << 5) will clear bit 5

Martin

Re: change individual bits in a byte

Posted: Sat Nov 25, 2023 9:38 am
by DirkB
Hello Martin,

many thanks for that. Is it also possible to set a bit in a byte by the value of a boolean variable,
like for example bit 5 (or any other bit) gets the value of the boolean variable?

thanks
Dirk

Re: change individual bits in a byte

Posted: Sat Nov 25, 2023 10:12 am
by DirkB
Me again,
Reading a byte via var1 = var2 & 4 - (4 - 2) always gives the value of the bit,
such as bit 1 = 1(0), bit 2 = 2(0), bit 3 = 4(0), bit 4 = 8(0) etc. Can each bit
be read out as set (1) or not set (0)?

Dirk

Re: change individual bits in a byte

Posted: Sat Nov 25, 2023 10:25 am
by mnfisher
Hi Dirk,

I don't think there is a way to set on the value of a boolean other than using a if ... else ... (conditional)

There is a way to always read true or false (as 1 or 0 - note any non zero value is treated as true)

.set = ((.var & 0b100) != 0) // Where set is a boolean - will always be set to true (1) if bit 2 is set for example (or you can shift the result of the and right (using >> 2 in this case)- I'm not sure if there is a speed or space advantage to either approach)
Similarly .nset = ((.var & 0b100) == 0) // Sets .nset to true if the bit is 0

Martin

Re: change individual bits in a byte

Posted: Sat Nov 25, 2023 10:28 am
by mnfisher
Note that you can also set / clear multiple bits at once.