Skip to content

Instantly share code, notes, and snippets.

@Bloody-Badboy
Last active July 4, 2018 03:57
Show Gist options
  • Save Bloody-Badboy/a6e70dc5ea0130478031a2773450faab to your computer and use it in GitHub Desktop.
Save Bloody-Badboy/a6e70dc5ea0130478031a2773450faab to your computer and use it in GitHub Desktop.
Conversion algorithms for converting HSL to RGB and RGB to HSL vice versa in C
#include <stdio.h>
static void hueToRgb(unsigned int *c, float p, float q, float t) {
if (t < 0.0f)
t += 1.0f;
if (t > 1.0f)
t -= 1.0f;
if (t < 0.166666)
*c = (unsigned int) ((q + (p - q) * 6 * t) * 100);
else if (t < 0.5)
*c = (unsigned int) (p * 100);
else if (t < 0.666666)
*c = (unsigned int) ((q + (p - q) * (.666666 - t) * 6) * 100);
else
*c = (unsigned int) (q * 100);
}
/*
* Converts an RGB color value to HSL.
*/
void RGBToHSL(unsigned int r, unsigned int g, unsigned int b, float hsl[]) {
float red, green, blue;
float max, min, delta;
float H, S, L;
red = (float) r / 255.0f;
green = (float) g / 255.0f;
blue = (float) b / 255.0f;
max = red > (green > blue ? green : blue) ? red : green > blue ? green : blue;
min = red < (green < blue ? green : blue) ? red : green < blue ? green : blue;
H = S = L = 0;
L = (max + min) / 2;
if (max != min) {
delta = max - min;
S = delta / (L < .50 ? max + min : 2 - max - min);
if (max == red) {
H = (green - blue) / (delta);
} else if (max == green) {
H = 2 + (blue - red) / delta;
} else if (max == blue) {
H = 4 + (red - green) / delta;
}
H /= 6;
}
hsl[0] = H;
hsl[1] = S;
hsl[2] = L;
}
void HSLToRGB(float H, float S, float L, int rgb[]) {
unsigned int red, green, blue;
float p, q;
if (S == 0) {
red = green = blue = (unsigned int) (L * 100);
} else {
p = L < .50 ? L * (1 + S) : L + S - (L * S);
q = 2 * L - p;
hueToRgb(&red, p, q, H + .33333f);
hueToRgb(&green, p, q, H);
hueToRgb(&blue, p, q, H - .33333f);
}
red = (unsigned int) (((((float) red) / 100) * 255) + 0.5);
green = (unsigned int) (((((float) green) / 100) * 255) + 0.5);
blue = (unsigned int) (((((float) blue) / 100) * 255) + 0.5);
rgb[0] = red;
rgb[1] = green;
rgb[2] = blue;
}
int main() {
const int red = 0x80, green = 0x80, blue = 0x80;
float hsl[3];
int rgb[3];
RGBToHSL(red, green, blue, hsl);
printf("HSL(%f,%f,%f)\n", hsl[0], hsl[1], hsl[2]);
HSLToRGB(hsl[0], hsl[1], hsl[2], rgb);
printf("RGB(%d,%d,%d)\n", rgb[0], rgb[1], rgb[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment