Packing A Color


Colors are often expressed as hex eg: 0xFF00FFFF, but colors are also expressed as floats and chars. it can be nice to pack a color into a uint32_t rather than dealing with an array of components. Here is how…

/* color.c */
#include <stdint.h>
#include <stdio.h>

int
main() {

  /* with a hex value */

  uint32_t color = 0xFF00FFFF;

  uint8_t red = (uint8_t)((color >> 24) & 0xFF);
  uint8_t green = (uint8_t)((color >> 16) & 0xFF);
  uint8_t blue = (uint8_t)((color >> 8) & 0xFF);
  uint8_t alpha = (uint8_t)((color >> 0) & 0xFF);

  printf("Color: %d %d %d %d\n", red, green, blue, alpha);

  /* with color components */
  red = 32;
  green = 64;
  blue = 128;
  alpha = 255;

  color = (uint32_t)((red << 24) | (green << 16) | (blue << 8) | (alpha << 0));

  red = (uint8_t)((color >> 24) & 0xFF);
  green = (uint8_t)((color >> 16) & 0xFF);
  blue = (uint8_t)((color >> 8) & 0xFF);
  alpha = (uint8_t)((color >> 0) & 0xFF);

  printf("Color: %d %d %d %d\n", red, green, blue, alpha);

  return 0;
}

Outputs …

Color: 255 0 255 255
Color: 32 64 128 255

Compile and run with GCC

gcc color.c && ./a.out

or Clang

clang color.c && ./a.out