Bit Manipulation (Copy)
Cheat Sheet: A Level Computer Science – Binary Shifts & Bit Manipulation
1. Binary Shifts
| Type | Shift Direction | Effect |
|---|---|---|
| Logical Shift Left (LSL) | Shifts bits left, inserts 0s on the right | Each shift multiplies value by 2 |
| Logical Shift Right (LSR) | Shifts bits right, inserts 0s on the left | Each shift divides value by 2 (integer) |
| Arithmetic Shift Right | Preserves sign bit (for 2’s complement values) | Used with signed binary numbers |
| Cyclic Shift | Bits wrap around the end | No bits lost; rotates the pattern |
2. Bit Manipulation for Device Control & Monitoring
Use Cases:
- Toggle LEDs
- Read sensor states
- Set device configuration bits
- Monitor flags and status registers
3. Bit Masking Operations
| Operation | Purpose | Example Effect |
|---|---|---|
| AND | Clear bits / Test if specific bits are 1 | AND B11110000 masks upper 4 bits |
| OR | Set specific bits to 1 | OR B00000001 sets the rightmost bit |
| XOR | Toggle specific bits | XOR B00001111 flips the lowest 4 bits |
4. Instructions and Usage
| Instruction | Effect |
|---|---|
AND #n/Bn/&n |
ACC ← ACC AND immediate value |
AND <address> |
ACC ← ACC AND memory[address] |
OR #n/Bn/&n |
ACC ← ACC OR immediate value |
OR <address> |
ACC ← ACC OR memory[address] |
XOR #n/Bn/&n |
ACC ← ACC XOR immediate value |
XOR <address> |
ACC ← ACC XOR memory[address] |
LSL #n |
Logical shift ACC left by n bits, insert 0s on right |
LSR #n |
Logical shift ACC right by n bits, insert 0s on left |
5. Bit Masking Examples
Test a Bit
To test if bit 3 is ON (counting from 0):
AND B00001000- Result: If ACC ≠ 0, bit 3 is ON
Set a Bit
To set bit 2 to 1:
OR B00000100
Clear a Bit
To clear bit 5 (make it 0):
AND B11011111
Toggle a Bit
To flip bit 0:
XOR B00000001
6. Labels and Addressing
| Syntax | Explanation |
|---|---|
<label>: <opcode> <operand> |
Defines an instruction with a label for referencing |
<label>: <data> |
Assigns symbolic name to data stored in memory |
#n |
Immediate decimal number |
Bn |
Immediate binary number |
&n |
Immediate hexadecimal number |
<address> |
Can be direct or symbolic memory location |
