Page 1 of 1
Defining a variable that is only 1 bit in size
Posted: Mon Dec 17, 2007 12:00 am
by Ron
Hi,
When I create a variable I must use an entire byte. I want to be able to define a variable as a bit so I do not waste so much memory.
How do you do it?
Thanks
Ron
Posted: Mon Dec 17, 2007 10:53 am
by Sean
Hi Ron,
The best way to store single bits of data (or small combinations of bits) is to use the AND, OR and XOR functions in a calculation block. These commands can be used to manipulate individual bits within a byte or integer variable.
If you create a variable called Flags:
A bit can be set by ORing it with a 1
Flags = Flags OR 4 will force bit 2 to be set
A more convenient notation, using the bit shift function, might be:
Flags = Flags OR (1 << 2)
Clearing the same bit can be done by ANDing it with a 0;
Flags = Flags AND NOT(1 << 2)
The bit can be toggled by XORing it with a 1;
Flags = Flags XOR (1 << 2)
The bit can be tested by ANDing it with a 1;
IF Flags AND (1 << 2)
It is not worth doing this if you are only dealing with a single variable of this type, as it will still be stored as a byte (the minimum memory size the controller will handle). But if you have several single bit variables they can be packed into a single byte or integer, using a different bit for each flag, by using these techniques.
The savings in data memory will be offset by a slightly larger program and slight reduction in operating speed due to the additional operations