IGNORED

# Is this the best way to flip a bit?

## Recommended Posts

Is this the best way to flip a bit from off to on or on to off:

a{1} = !a{1}

Thanks.

##### Share on other sites

I use this to flip a bit:

`a ^ 1`

##### Share on other sites

Is this the best way to flip a bit from off to on or on to off:

a{1} = !a{1}

Thanks.

the ^ operator generates a lot less code.

##### Share on other sites

Is this the best way to flip a bit from off to on or on to off:

a{1} = !a{1}

Thanks.

the ^ operator generates a lot less code.

Thanks.

##### Share on other sites

Either I didn't know or I forgot that XOR could flip a bit. Can somebody post how you'd use XOR to flip each of the 8 bits individually? A made a little chart to fill in to make it easier:

```a{0} = !a{0}	same as	a ^

a{1} = !a{1}	same as	a ^ 1

a{2} = !a{2}	same as	a ^

a{3} = !a{3}	same as	a ^

a{4} = !a{4}	same as	a ^

a{5} = !a{5}	same as	a ^

a{6} = !a{6}	same as	a ^

a{7} = !a{7}	same as	a ^```

Thanks.

##### Share on other sites

Can someone also post a little example of how this works? It doesn't seem to be working correctly in my program. I must not be doing it right.

##### Share on other sites

Can someone also post a little example of how this works? It doesn't seem to be working correctly in my program. I must not be doing it right.

You would do

`   a = a ^ %xxxxxxxx`

where %xxxxxxxx is a bit pattern you want to flip a with. Anywhere there's a 0, the bit will be left as is. Anywhere there's a 1, the bit will be flipped. So for example if you wanted to flip bit 4, you would do

`   a = a ^ %00010000`

Bits 0-3, as well as bits 5-7, will stay as they are, and bit 4 will be flipped. You can also use decimal or hex values that represent the same bit pattern. For example

```   dim frame = a
frame = 0

loop

drawscreen
frame = frame ^ 1

goto loop```

will flip frame between 0 and 1, so you can tell whether you're on an odd frame or an even frame-- which would be useful if you were doing things that need to be split across two frames, and needed a way to tell if it's time to do stuff1 or stuff2.

Michael

##### Share on other sites

Thanks. Now I know why it wasn't working. I was using the wrong number with '^'.

```a{0} = !a{0}	same as	a = a ^ 1

a{1} = !a{1}	same as	a = a ^ 2

a{2} = !a{2}	same as	a = a ^ 4

a{3} = !a{3}	same as	a = a ^ 8

a{4} = !a{4}	same as	a = a ^ 16

a{5} = !a{5}	same as	a = a ^ 32

a{6} = !a{6}	same as	a = a ^ 64

a{7} = !a{7}	same as	a = a ^ 128```

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.