Skip to content

Instantly share code, notes, and snippets.

@ljmccarthy
Last active September 26, 2023 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljmccarthy/3ee797f6f94771d8dd5e41ef328eafc2 to your computer and use it in GitHub Desktop.
Save ljmccarthy/3ee797f6f94771d8dd5e41ef328eafc2 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#define RGB(r,g,b) (((r) & 0xFF) | (((g) & 0xFF) << 8) | (((b) & 0xFF) << 16))
#define RED(rgb) ((rgb) & 0xFF)
#define GRN(rgb) (((rgb) >> 8) & 0xFF)
#define BLU(rgb) (((rgb) >> 16) & 0xFF)
uint32_t rgb_from_hsl(float hue, float sat, float lig)
{
float C = (1.0f - fabsf(2.0f * lig - 1.0f)) * sat; // chroma
float H = hue / 60.0f;
float X = C * (1.0f - fabsf(fmodf(H, 2.0f) - 1));
float R,G,B;
switch ((int)H) {
default:
case 0: R=C, G=X, B=0; break;
case 1: R=X, G=C, B=0; break;
case 2: R=0, G=C, B=X; break;
case 3: R=0, G=X, B=C; break;
case 4: R=X, G=0, B=C; break;
case 5: R=C, G=0, B=X; break;
}
float m = lig - C/2.0f;
int r = (R+m) * 255.0f;
int g = (G+m) * 255.0f;
int b = (B+m) * 255.0f;
return RGB(r, g, b);
}
int main()
{
uint32_t rgb = rgb_from_hsl(260, 1.0, 0.6);
printf("%u, %u, %u\n", RED(rgb), GRN(rgb), BLU(rgb));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment