Published by Patrick Mutisya · 8 days ago
Show understanding of how bit manipulation can be used to monitor and control a device.
In embedded systems and hardware interfacing a single byte (8 bits) can represent up to 256 different states. By treating each bit as a flag we can:
| Operator | Name | Effect |
|---|---|---|
| & | AND | Result bit is 1 only if both operands are 1. |
| | | OR | Result bit is 1 if either operand is 1. |
| ^ | XOR | Result bit is 1 if operands differ. |
| ~ | NOT | Flips every bit (two's complement). |
| << | Left shift | Moves bits left, inserting zeros on the right. |
| >> | Right shift | Moves bits right, discarding low‑order bits. |
Consider an 8‑bit register PORTA that controls a set of LEDs and reads a set of switches.
Bit 7 6 5 4 3 2 1 0
| | | | | | | +--- Switch 0 (input)
| | | | | | +----- Switch 1 (input)
| | | | | +------- LED 0 (output)
| | | | +--------- LED 1 (output)
| | | +----------- Unused
| | +------------- Unused
| +--------------- Unused
+----------------- Unused
Bit masks isolate or modify specific bits. The mask for LED 0 (bit 2) is \$1 \ll 2 = 0b00000100 = 0x04\$.
Typical masks for the example above:
| Name | Bit Position | Mask (binary) | Mask (hex) |
|---|---|---|---|
| LED0 | 2 | 0b00000100 | 0x04 |
| LED1 | 3 | 0b00001000 | 0x08 |
| SW0 | 0 | 0b00000001 | 0x01 |
| SW1 | 1 | 0b00000010 | 0x02 |
To test whether Switch 1 is ON:
\$\text{status} = \text{PORTA} \; \&\; 0x02\$
If status is non‑zero, the switch is high; otherwise it is low.
Turn LED 0 ON (set bit 2):
\$\text{PORTA} = \text{PORTA} \;|\; 0x04\$
Turn LED 0 OFF (clear bit 2):
\$\text{PORTA} = \text{PORTA} \;\&\; \sim0x04\$
Toggle LED 1 (invert bit 3):
\$\text{PORTA} = \text{PORTA} \; \hat{}\; 0x08\$
Assume a microcontroller reads an 8‑bit status register SENSOR_STATUS where:
The following pseudo‑code demonstrates how to react to the alarm:
if (SENSOR_STATUS & 0x80) != 0: # Over‑temperature?
activatecoolingfan() # set control bit
else:
deactivatecoolingfan()
Here 0x80 = 1 << 7 isolates the alarm flag.
Sometimes several conditions must be met before an action is taken. Using logical AND on masked bits achieves this:
\$\text{critical} = (\text{SENSOR_STATUS} \& 0xC0) == 0xC0\$
Explanation: 0xC0 = 0b11000000 masks bits 7 and 6. The expression is true only when both the alarm and fault bits are set.
& to read a flag, | to set, &~ to clear, and ^ to toggle.