Simvik

Reverse the bits of a byte

Mirror a byte so bit 7 becomes bit 0. A medium embedded C problem (Bit manipulation), run and graded in the browser.

medium · Bit manipulation · bit-order

Return x with its bit order reversed: bit 0 swaps with bit 7, bit 1 with bit 6, and so on. For example 0x01 becomes 0x80.

You need this when a peripheral shifts data out LSB-first and the protocol expects MSB-first.

Starter code

uint8_t reverse8(uint8_t x) {
  // Return x mirrored: bit 0 <-> bit 7, bit 1 <-> bit 6, ...
  return x;
}

Example tests

Lowest bit moves to the top

printf("0x%02X\n", reverse8(0x01));

Expected output:

0x80

Mixed pattern

printf("0x%02X\n", reverse8(0xB4));

Expected output:

0x2D

Learn it first

  • Bit manipulation · Masks, shifts, fields and the idioms every register access is built from.

More Bit manipulation problems