Clearing Individual Bits
Now we need to talk about how to turn things off.
- This time we will exploit the properties of the AND instruction:
- 0 AND 0 = 0; 0 AND 1 = 0; i.e. 0 AND x = 0
- In other words, when we AND anything with 0, we always get a 0.
- 1 AND 0 = 0; 1 AND 1 = 1; i.e. 1 AND x = x
- In other words, when we AND anything with 1, it doesn't change.
- We have to make our masks in a different way for AND operations:
- We put 1's where we want the bit to stay as it is,
and we put 0's where we want to be sure that the bit is a 0.
- Now let's suppose that both lights are on, and we want to turn light B off.
- We would need bit 0 off and bit 1 on in our control register.
- I.e. we want our register to have the value 10 binary; that's 2 in decimal or hex.
- Suppose instead that we wanted to turn off light A.
- We would need bit 1 off and bit 0 on, i.e. a value of 01 binary; i.e. 1 in decimal or hex).
- To turn off light A, the mask should be 1: andi $s0 $s0 1
- To turn off light B, the mask should be 2: andi $s0 $s0 2
- To turn off both lights at once, the mask should be 0: andi $s0 $s0 0
- If the mask were to be 3, neither light would change.
- Here's a trick that may come in handy once in a while:
- Suppose that we want to turn off all the lights that are on and turn on all the lights that are off.
- xori $s0 $s0 0xFFFFFFFF # reverse all the bits in $s0
- We obviously need to figure out how this works
- XOR is like OR except that 1 XOR 1 = 0
- So the rule is: x XOR y = 1 if x and y are different, and x XOR y = 0 if x and y are the same
- In particular, 0 XOR 1 = 1, and 1 XOR 1 = 0
- I.e. x XOR 1 = not x (where not 0 = 1; not 1 = 0)
- Remember that 0xFFFFFFFF is 32 bits that are all 1's,
so using it as a mask for an XOR reverses all the bits of the other operand.
- In other words, MIPS does not need a NOT operator because XOR against 0xFFFFFFFF does that job.
- Here's a puzzler for you: suppose $s0 controls 32 lights; what does this do?