Simvik

Interleave two bytes

Spread the bits of two bytes into alternating positions of a 16-bit value. A hard embedded C problem (Bit manipulation), run and graded in the browser.

hard · Bit manipulation · bit-spreading

Return a 16-bit value in which the bits of x occupy the even positions (0, 2, 4, ...) and the bits of y occupy the odd positions (1, 3, 5, ...).

Bit i of x goes to bit 2 * i, and bit i of y goes to bit 2 * i + 1. This is called a Morton code.

Starter code

uint16_t interleave8(uint8_t x, uint8_t y) {
  // x fills bits 0, 2, 4, ... and y fills bits 1, 3, 5, ...
  return 0;
}

Example tests

Only x

printf("0x%04X\n", interleave8(0x0F, 0x00));

Expected output:

0x0055

Only y

printf("0x%04X\n", interleave8(0x00, 0x0F));

Expected output:

0x00AA

Learn it first

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

More Bit manipulation problems