Shop OBEX P1 Docs P2 Docs Learn Events
Need to invert a bit in a byte — Parallax Forums

Need to invert a bit in a byte

JonmarJonmar Posts: 9
edited 2008-08-29 14:06 in BASIC Stamp
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 smile.gif

Jon

Comments

  • FranklinFranklin Posts: 4,747
    edited 2008-08-29 01:07
    Will the bit be different each time through the subroutine or always the same bit?

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    - Stephen
  • PJAllenPJAllen Banned Posts: 5,065
    edited 2008-08-29 01:24
    ·
    somevariable  VAR  Byte
     
    IF somevariable.BIT0 = 0 THEN
    somevariable.BIT0 = 1
    ELSE
    somevariable.BIT0 = 0
    ENDIF
    
  • Tracy AllenTracy Allen Posts: 6,662
    edited 2008-08-29 04:00
    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

    Post Edited (Tracy Allen) : 8/29/2008 4:44:37 AM GMT
  • JonmarJonmar Posts: 9
    edited 2008-08-29 14:06
    Franklin,

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

    Jon
Sign In or Register to comment.