</>EmbeddedInterview
← All problems · Bit Manipulation

Reverse the Bits of a Byte

Easy

Write uint8_t reverse8(uint8_t b) that mirrors the bit order: bit 0 becomes bit 7, bit 1 becomes bit 6, and so on. For example 0x01 becomes 0x80 and 0xB0 becomes 0x0D.

This comes up when a peripheral sends LSB-first data but your protocol expects MSB-first.

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Swap the two nibbles, then swap pairs of bits within each nibble, then swap adjacent bits.

#include <stdio.h>
#include <stdint.h>

uint8_t reverse8(uint8_t b)
{
    b = (uint8_t)((b & 0xF0u) >> 4 | (b & 0x0Fu) << 4);
    b = (uint8_t)((b & 0xCCu) >> 2 | (b & 0x33u) << 2);
    b = (uint8_t)((b & 0xAAu) >> 1 | (b & 0x55u) << 1);
    return b;
}

Three swap stages of width 4, 2 and 1 reverse 8 bits in constant time with no loop. The masks select the upper and lower half of each group. The casts back to uint8_t matter because of integer promotion: the expressions are computed as int.

Alternatives: a loop that shifts bits out of b and into the result (8 iterations), or a 256-byte lookup table in flash for the fastest speed. On ARMv7-M, __RBIT(x) >> 24 does it in one instruction.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    CHECK(reverse8(0x01) == 0x80);
    CHECK(reverse8(0x80) == 0x01);
    CHECK(reverse8(0xB0) == 0x0D);
    CHECK(reverse8(0xFF) == 0xFF);
    CHECK(reverse8(0x00) == 0x00);
    for (unsigned i = 0; i < 256; i++) CHECK(reverse8(reverse8((uint8_t)i)) == i);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}