Skip to content

Instantly share code, notes, and snippets.

@fullnitrous
Last active October 20, 2018 22:43
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 fullnitrous/7af4970c67d0c75e88b4736fc95dbbba to your computer and use it in GitHub Desktop.
Save fullnitrous/7af4970c67d0c75e88b4736fc95dbbba to your computer and use it in GitHub Desktop.
Proper conversion of RGB to HSL
/*
RGB to HSL
Compile with: gcc rgb_to_hsl.c -lm -o rgb_to_hsl
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
struct hsl
{
int h;
float s;
float l;
};
struct rgb
{
uint8_t r;
uint8_t g;
uint8_t b;
};
float max_3(float x, float y, float z)
{
x = (x > y) ? x : y;
x = (x > z) ? x : z;
return x;
}
float min_3(float x, float y, float z)
{
x = (x < y) ? x : y;
x = (x < z) ? x : z;
return x;
}
struct hsl rgb_to_hsl(uint8_t r, uint8_t g, uint8_t b)
{
struct hsl output;
float rf = r / 255.0;
float gf = g / 255.0;
float bf = b / 255.0;
float max = max_3(rf, bf, gf);
float min = min_3(rf, bf, gf);
float h, s, l;
h = s = l = (max + min) / 2.0;
if(max == min)
{
h = s = 0.0;
}
else
{
float d = max - min;
s = (l > 0.5) ? d / (2.0 - min - max) : d / (max + min);
if(max == rf)
{
h = (gf - bf) / d;
if(gf < bf) h += 6.0;
}
else if(max == gf) h = (bf - rf) / d + 2.0;
else if(max == bf) h = (r - g) / d + 4.0;
h = h / 6.0;
}
output.h = roundf(360 * h);
output.s = s;
output.l = l;
return output;
}
int main(void)
{
struct rgb input = {230, 67, 34};
struct hsl output = rgb_to_hsl(input.r, input.g, input.b);
printf("\nConverted rgb(%d, %d, %d) to rgb(%d°, %.2f%%, %.2f%%)\n\n",
input.r, input.g, input.b,
output.h, output.s * 100, output.l * 100);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment