Show understanding of how bit manipulation can be used to monitor/control a device

4.3 Bit Manipulation

What is Bit Manipulation?

Bit manipulation means using bitwise operators to change, test or read individual bits in a binary number. Think of a binary number as a row of tiny switches that can be either ON (1) or OFF (0).
🔧 Each switch controls a specific feature of a device.

Common Bitwise Operators

  • AND (&) – keeps a bit ON only if it is ON in both operands.
  • OR (|) – turns a bit ON if it is ON in either operand.
  • XOR (^) – flips a bit if the other operand’s bit is ON.
  • NOT (~) – flips every bit.
  • Left Shift (<<) – moves bits to the left, adding zeros on the right.
  • Right Shift (>>) – moves bits to the right, discarding the rightmost bits.

Setting, Clearing, Toggling Bits

These are the three most common bitwise tricks used to control device states.

  1. Set a bit – use OR with a mask: value = value | mask.
    Example: To turn on bit 3, use mask 0b00001000 (decimal 8).
  2. Clear a bit – use AND with the inverse mask: value = value & ~mask.
    Example: To turn off bit 2, use mask 0b00000100 (decimal 4).
  3. Toggle a bit – use XOR with a mask: value = value ^ mask.
    Example: To flip bit 1, use mask 0b00000010 (decimal 2).

Monitoring a Device

Suppose a sensor sends a 16‑bit status word. Each bit represents a different sensor flag.

Bit Meaning
0 Temperature OK
1 Pressure OK
2 Battery Low

To check if the battery is low, test bit 2:

if (status & 0b00000100) { /* battery low */ }

Controlling a Device

Imagine a robot arm with 8 control bits: each bit turns a motor on or off.

  1. Read the current control word from the robot.
  2. Set the bit that controls the gripper: control = control | 0b00001000.
  3. Clear the bit that stops the arm: control = control & ~0b00000001.
  4. Send the updated control word back to the robot.

Because bitwise operations are very fast, the robot can react in microseconds! 🚀

Exam Tips

  • Show the binary representation of numbers when explaining bitwise operations.
  • Use masks that are powers of two (e.g., 0b00010000) to target a single bit.
  • Explain the difference between AND and OR with a simple truth table.
  • Remember that ~x flips all bits – be careful with signed integers.
  • When asked to write code, include comments that describe each step (set, clear, toggle).

Practice Question

Given a 8‑bit status register status = 0b10101100, write the expression to:

  1. Check if bit 5 (counting from 0) is set.
  2. Turn on bit 2.
  3. Turn off bit 7.

Answer (in code):

// 1. Check bit 5
if (status & 0b00100000) { /* bit 5 is ON */ }

// 2. Turn on bit 2
status = status | 0b00000100;

// 3. Turn off bit 7
status = status & ~0b10000000;

Revision

Log in to practice.

3 views 0 suggestions