Shifts
| Shift | Effect on the value | Example (8 bits) |
|---|---|---|
| Left by 1 place | Multiplies by 2 | 00010110 (22) → 00101100 (44) |
| Left by 2 places | Multiplies by 4 | 00010110 (22) → 01011000 (88) |
| Right by 1 place | Divides by 2 | 00010110 (22) → 00001011 (11) |
| Right by 3 places | Divides by 8 | 01011000 (88) → 00001011 (11) |
Shifting left by n places multiplies the number by 2^n, and shifting right by n places divides it by 2^n. A shift is much quicker for the processor than a full multiplication or division.
• A 1 shifted off the left-hand end is lost (overflow): 11000000 (192) shifted left 1 place gives 10000000 (128), not 384
• A 1 shifted off the right-hand end is lost, so the result is rounded down: 00001011 (11) shifted right 1 place gives 00000101 (5), not 5.5
Masks
| Operation | Where the mask has a 1 | Where the mask has a 0 | Used to |
|---|---|---|---|
| AND | The bit is kept | The bit becomes 0 | Clear bits, or pick out (extract) bits |
| OR | The bit becomes 1 | The bit is kept | Set bits to 1 |
| XOR | The bit is flipped | The bit is kept | Flip (toggle) bits |
Apply the mask 00001111 to the value 10110110.
| Row | AND | OR | XOR |
|---|---|---|---|
| Value | 10110110 | 10110110 | 10110110 |
| Mask | 00001111 | 00001111 | 00001111 |
| Result | 00000110 | 10111111 | 10111001 |
• OR set the right-hand four bits to 1
• XOR flipped the right-hand four bits
• To test whether a number is odd, AND it with 00000001. A result of 1 means the last bit was set
• In ASCII, 'A' is 01000001 and 'a' is 01100001. OR with 00100000 turns a capital letter into lower case, and AND with 11011111 turns it back
• XOR with 11111111 flips every bit, which is the same as NOT
• Keep some bits and clear the rest: AND
• Force bits to 1: OR
• Flip bits: XOR
• Write the mask with the same number of bits as the value and work down each column