Shop OBEX P1 Docs P2 Docs Learn Events
Simple VAR question — Parallax Forums

Simple VAR question

JomsJoms Posts: 279
edited 2008-11-23 02:31 in BASIC Stamp
I am trying to invert a variable.· I am fairly sure it is pretty simple, but I just can't seem to figure it out.· I have a variable that I access at bit level and want to invert all of the bits....· Example...

%11111111··· I need this to equal·· ·%00000000

I have tried multiplying by -1 and also tried puting a minus sign in front of the number to make it a signed number, but it always seems to add a one when I make it a signed number.

I probably just don't understand what I am doing here, but if someone could chime in and give me a clue, that would be great...· Thanks in advance...

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2008-11-23 02:21
    You can use the bit-wise logical not (!) operator. Remember that this inverts all the bits, so, if you're using 16-bit words, the high order bits will be affected. If you're working with 8-bit bytes, the extra bits will get truncated, so it'll work out.

    You can also use exclusive or (^) to just invert some of the bits.

    If X is a byte variable, you can write: X = !X
    You can also write: X = X ^ %11111111

    If you only want the least significant 7 bits inverted, you would write: X = X ^ %1111111
  • PJAllenPJAllen Banned Posts: 5,065
    edited 2008-11-23 02:21
    ~
    some_var = ~some_var
  • Bruce BatesBruce Bates Posts: 3,045
    edited 2008-11-23 02:22
    Joms -


    The is one PBASIC operator you can use to perform that task. Here is a description and example from the PBASIC Help file:

    quote

    ~ Invert Bits
    The Inverse operator (~) complements (inverts) the bits of a number. Each bit that contains a 1 is changed to 0 and each bit containing 0 is changed to 1. This process is also known as a "bitwise NOT" and one's compliment.

    ~0 = 1
    ~1 = 0

    end quote

    Variables operate the same way as the examples above.

    Regards,

    Bruce Bates

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    When all else fails, try inserting a new battery.
  • JomsJoms Posts: 279
    edited 2008-11-23 02:31
    THANKS!!! That did exactly what I wanted to too.... Thanks so much for all your help!
Sign In or Register to comment.