image Tutorial on Bitwise Operations

So far, all operations on variable attributes are arithmetic, such as add and subtract. However, sometimes we would like to perform an operation on a variable attribute that is not arithmetic, such as bitwise and, bitwise or, right shift, or left shift. Consider game plan below.

There are 5 foxes and 5 puppies.
There is a rabbit controlled with mouse.
The s2 of the rabbit is initially -2.
When the rabbit touches a fox, the fox explodes.
When the rabbit touches a fox, the s2 of the rabbit multiplies by s2 of the rabbit.
Display s2 of the rabbit.
When the rabbit touches a puppy, the puppy explodes.
When the rabbit touches a puppy, the s2 of the rabbit bitand 3.

What do you think would happen? When you run the above game plan, you will see that when the rabbit touches a puppy, the variable s1 is truncated, as if it is remainder of dividing by 4.


Try it yourself: Now try changing the bitwise operations to bitor, bitrightshift, bitleftshift in the last sentence of the above game plan and see what would happen.
Consider the following game plan:

There are 20 rabbits.
When the rabbit is not dead, the x1 of the rabbit equals the index of the rabbit.
When the rabbit is not dead, the x1 of the rabbit bitand 1.
When the x1 of the rabbit equals 0, the rabbit moves right.
When the x1 of the rabbit equals 1, the rabbit moves left.

What do you think x1 of the rabbit represents? Since it is set to be the index of the rabbit, and then it is bitwise ANDing with 1, it will indicate whether the index of the rabbit is even or odd. If it is 0, it is even. Otherwise, it is odd. What do you think it will do? Try it out and see.


Now, we will extend the above game plan a little to the following:

There are 20 rabbits.
When the rabbit is not dead, the x1 of the rabbit equals the index of the rabbit.
When the rabbit is not dead, the x1 of the rabbit bitand 3.
When the x1 of the rabbit equals 0, the rabbit moves right.
When the x1 of the rabbit equals 1, the rabbit moves left.
When the x1 of the rabbit equals 2, the rabbit moves up.
When the x1 of the rabbit equals 3, the rabbit moves down.

What do you think x1 of the rabbit now represents? Since it is bitwise ANDing with 3 (least significant 2 bits), it will result in one of 4 possible values: 0, 1, 2, or 3. What do you think it will now do? Try it out and see.


Next page

Tutorials Home