Easier Way to read certain bit of a byte or long?
SuperCricket
Posts: 17
I've been trying to keep variable usage to a minimum for a program. I wanted to have on byte and flip each of the 8 bits depending on which of the 8 events is happening or not, rather than have 8 variables declared or an array.
How can I access a certain bit of the byte?
So far the hack job method I came up with is ANDing the variable depending on which bit I want to read and then shifting it over to see if its a one. Example:
To check if the 3rd from left bit is a 1
10101100
00100000 AND
00100000
Then shift right 5 places, and check to see if variable now equals 1.
=00000001
And to flip a desired bit I would have to XOR it back.
01001100
00100000 XOR
01101100
Above flips only the 3rd bit to a 1.
This is pretty rediculous and the resulting code to handle all of this probably uses more memory than just delaring 8 one-byte variables.
Any ideas?
Post Edited (SuperCricket) : 2/24/2009 1:09:30 AM GMT
How can I access a certain bit of the byte?
So far the hack job method I came up with is ANDing the variable depending on which bit I want to read and then shifting it over to see if its a one. Example:
To check if the 3rd from left bit is a 1
10101100
00100000 AND
00100000
Then shift right 5 places, and check to see if variable now equals 1.
=00000001
And to flip a desired bit I would have to XOR it back.
01001100
00100000 XOR
01101100
Above flips only the 3rd bit to a 1.
This is pretty rediculous and the resulting code to handle all of this probably uses more memory than just delaring 8 one-byte variables.
Any ideas?
Post Edited (SuperCricket) : 2/24/2009 1:09:30 AM GMT
Comments
For testing bits, you can make use of the fact that Boolean expressions are false if they're zero and true if they're non-zero so you can have IF X & mask. This will test for the masked bits in X and the IF will succeed if and of the masked bits are non-zero.
You can use DIRB and OUTB as Bit addressable registers on the current Prop, because this registers are implemented as RAM and not connected to a Port. This gives you 2*32 bits.
If you not use the counters then also PHSx and FRQx can be used.
To write a Bit:
DIRB[noparse][[/noparse]bit] := 1
To read/check a Bit:
value := DIRB[noparse][[/noparse]bit]
if DIRB[noparse][[/noparse]bit] == 1
...
Andy
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Timothy D. Swieter, E.I.
www.brilldea.com - Prop Blade, LED Painter, RGB LEDs, uOLED-IOC, eProto for SunSPOT, BitScope
www.tdswieter.com
To elaborate on what Mike Green has said...
variable &= !|<Bit·········· '<-- To Turn Off a Bit
variable·|= |<Bit············ '<-- To Turn On a Bit···
variable·^= |<Bit············· '<-- To Toggle a Bit
BitValue := (variable & |<Bit)>>Bit··· '<-- To Read a Bit
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Beau Schwabe
IC Layout Engineer
Parallax, Inc.
Post Edited (Beau Schwabe (Parallax)) : 2/25/2009 5:31:37 AM GMT