Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
NOT operator to reverse bits ?
#1
I've got a variable defined as INTEGER which holds 8 status flags (1=status on, 0=status off), and I'm trying to figure out a quick way via AND/OR/NOT to be able to toggle specific bits. To clarify:

Megan.Status is INTEGER

1 = flag 1
2 = flag 2
4 = flag 3
8 = flag 4
16 = flag 5
32 = flag 6
64 = flag 7
128 = flag 8

If I have flags 2, 4, and 5, then Megan.Status = 2 + 8 + 16 = 26. Therefore, Megan.Status can range between 0 (no flags), and 255 (all 8 flags).

Pushing a green button turns flags 3 and 5 on, regardless of other flags. I have represented button.green as 4 + 16 = 20.

Pushing a red button turns flags 3 and 5 off, regardless of other flags. I have represented button.red as 4 + 16 = 20, also.

Turning the status bits *on* is easy, I just do:
Code:
Megan.Status = Megan.Status OR button.green

But turning the bits *off* is giving me trouble. I thought at first that I could do:
Code:
Megan.Status = Megan.Status AND (NOT button.red)

I figured that NOT would reverse the bits of button.red so 1s would become 0s and vice-versa, leaving 0's for the toggled flags, then AND would switch those flags to 0.

Unfortunately, the NOT operator doesn't work how I expected it to, and I think it has something to do with the variables being 16-bit signed integers?

I want to take the value 127 (01111111) and NOT it to (10000000), then AND it with, say, (00010001) to result in (00000000). But when I NOT 127, I don't get 128, I get -128.

I don't care about the other 8 bits of the integer, I'm only looking to work with the lowest 8 bits for status flags.

So (sorry for the long back story), is there an easy way to do this using AND/OR/NOT/etc. ?

I hope this question made sense; I can provide more information if needed.

*peace*

~ Megan.
Reply
#2
You can use XOR to toggle bits.

Code:
number = 70
'this is 01000110

number = number XOR 128
'now it will be 11000110

number = number XOR 128
'now it will be 01000110 again


Yes indeed turning bits on can be done with OR. If a bit is already on, it will be left on.

Code:
number = 70
'this is 01000110

number = number OR 128
'now it is 11000110

Forcing bits to off is a bit more complex, but were actually doing it right.

Code:
number = 70
'this is 01000110

number = number AND NOT(64)
'now it is 00000110

number = 70
'this is 01000110 again

number = number AND NOT(6)
'now it is 01000000


Hope that made sense Smile
Reply
#3
Ahhhhh... I am so stupid.

Yeah, "a AND NOT b" works fine. It turns out that a few lines of code above, value "a" was being changed when it should not have, ironically due to use of OR:

Code:
IF ActType% = 3 OR 5

instead of

Code:
IF ActType% = 3 OR ActType% = 5

*sigh*

Thanks, anyway, for the response!

*peace*

~ Megan.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)