` Printed Icetips Article

Icetips Article



Par2: Setting bits in a Byte
2011-08-18 -- Bob Roos
 
variable = bor(variable,01h) ! turns on the right most bit
variable = band(variable,0FEh) ! turns it off
variable = bxor(variable,01h) ! flips it

Bruce Johnson adds:
x = BOR(x,SomeBit) ! turn it on
x = XBOR(x,SomeBit) ! flip it
x = BAND(x,255-SomeBit) ! turn it off

a couple of things I like to do here;

a) use an EQUATE to name the bit and
b) Use "binary" number syntax.

Consider for example the following;

Bit0   Equate(00000001b)
Bit1   Equate(00000010b)
Bit2   Equate(00000100b)
Bit3   Equate(00001000b)
Bit4   Equate(00010000b)
Bit5   Equate(00100000b)
Bit6   Equate(01000000b)
Bit7   Equate(10000000b)
BitMax  Equate(11111111b)

using the 'b' numbering format it's easy to see where the bit falls in the 
sequence.
And if say Bit3 and Bit4 always work together you can add an equate
ControlBits  Equate(00011000b)
and so on.

this allows yor code to be quite readable - for example

x = Bor(x,Bit3+Bit6) ! turn on Bit 3 and Bit 6
x = Bxor(Bit2) ! flip bit 2
x = Band(BitMax-Bit7-Bit1) ! turn off bit 7 and bit 1

The only consideration you should really have to worry about is whether you 
count the bits as
bit 1 to bit 8, or bit 0 to bit 7. That can go both ways, but usually I code 
it to match the documentation
I'm working from. If it's my decision I'll use Bit 1 so it's consistent with 
the rest of Clarion.



Printed November 21, 2024, 6:49 am
This article has been viewed/printed 35227 times.