</>EmbeddedInterview

How do you check whether bit n is the same in two registers?

EasyBit Manipulation

Short answer: XOR the two values; a 1 marks every bit that differs. Bit n is the same in both when ((a ^ b) >> n) & 1u is 0.

#include <stdbool.h>
#include <stdint.h>

bool same_bit(uint32_t a, uint32_t b, unsigned n)
{
    return (((a ^ b) >> n) & 1u) == 0;
}

Example: a = 0b1010, b = 0b1001, a ^ b = 0b0011. Bits 0 and 1 differ; bits 2 and 3 are the same.

Practical uses of "a ^ b"

  • Change detection: read the GPIO input register, XOR it with the previous reading, and the result shows which pins changed. changed & new_state gives rising edges and changed & ~new_state gives falling edges. c uint32_t now = GPIOA->IDR; uint32_t changed = now ^ last; uint32_t rising = changed & now; uint32_t falling = changed & ~now; last = now;
  • Comparing a register with an expected value under a mask: ((reg ^ expected) & mask) == 0 checks only the bits you care about.
  • Hamming distance: __builtin_popcount(a ^ b) counts differing bits, used in error-correction and checksums.

Follow-up: "Check whether all bits in a mask are the same": ((a ^ b) & mask) == 0.