Simvik

Pack an RGB565 pixel

Squeeze 24-bit colour into the 16-bit format small displays use. An easy embedded C problem (Structs, unions and memory layout), run and graded in the browser.

easy · Structs, unions and memory layout · bit-packing · displays

Small TFT displays store each pixel in 16 bits: red in bits 15..11, green in bits 10..5 and blue in bits 4..0.

Convert an 8-bit-per-channel colour by keeping the most significant 5 bits of red, 6 bits of green and 5 bits of blue.

Starter code

uint16_t rgb565(uint8_t r, uint8_t g, uint8_t b) {
  // rrrrr gggggg bbbbb
  return 0;
}

Example tests

Pure red

printf("0x%04X\n", rgb565(0xFF, 0x00, 0x00));

Expected output:

0xF800

Pure green

printf("0x%04X\n", rgb565(0x00, 0xFF, 0x00));

Expected output:

0x07E0

Learn it first

More Structs, unions and memory layout problems