Hello,
How can I change individual bits in a byte?
Thank you
Dirk
change individual bits in a byte
-
- Posts: 61
- http://meble-kuchenne.info.pl
- Joined: Thu Dec 10, 2020 3:55 pm
- Been thanked: 4 times
Re: change individual bits in a byte
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
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
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
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
-
- Valued Contributor
- Posts: 1008
- Joined: Wed Dec 09, 2020 9:37 pm
- Has thanked: 106 times
- Been thanked: 520 times
Re: change individual bits in a byte
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
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