PDA

View Full Version : Need to invert a bit in a byte



Jonmar
08-29-2008, 09:03 AM
Howdy all,

I need to Invert a single "bit" in a Byte without disturbing any of the other bits.
Upon entering the needed subroutine, I will know which bit that I need to affect.
Also I need to do this with a minimal amount of code.
I am using a BS2e module.

Any suggestions would be appreciated.

Thanks in advance http://forums.parallax.com/images/smilies/smile.gif

Jon

Franklin
08-29-2008, 09:07 AM
Will the bit be different each time through the subroutine or always the same bit?

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
- Stephen

PJ Allen
08-29-2008, 09:24 AM


somevariable VAR Byte

IF somevariable.BIT0 = 0 THEN
somevariable.BIT0 = 1
ELSE
somevariable.BIT0 = 0
ENDIF

Tracy Allen
08-29-2008, 12:00 PM
whichBit VAR NIB ' 0 to 7 for bit number to flip
myVar VAR BYTE ' variable that needs that one bit flipped
here:
myVar = myVar ^ DCD whichBit
' the bit is now flipped


For example, if whichBit=5, then DCD whichBit will equal %00100000 with the fifth bit set, and then the XOR, ^ in PBASIC causes that one bit to flip.

Another way, using the fact that bits in a byte can be array-addressed counting up from bit 0:


whichBit VAR NIB ' 0 to 7 for bit number to flip
myVar VAR BYTE ' variable that needs that one bit flipped
here:
myVar.bit0(whichBit) = ~myVar.bit0(whichBit) ' ~ is PBASIC NOT operator
' the bit is now flipped

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com (http://www.emesystems.com)

Post Edited (Tracy Allen) : 8/29/2008 4:44:37 AM GMT

Jonmar
08-29-2008, 10:06 PM
Franklin,

Might be same bit, but usually a different bit each time through sub routine.

Jon