# HSV to RGB Algorithm

3 September 2018 2 min read Category: programming Tags: color c algorithm

As an exercise I decided to make an HSV to RGB algorithm. I came up with it while making a C program to print to the terminal in full color.

It uses a could different functions. The first is a function to clamp a `double` to a `double` with values ranging from 1.0 to 0.0.

``````double clamp_double(double n){
n = (n > 1.0) ? 1.0 : n;
n = (n < 0.0) ? 0.0 : n;
return n;
}
``````

The second function calculates the value for a color channel based on hue.

``````double calc_hue(double h){
return clamp(-6 * fabs(ONE_THIRD - fmod(h, 1)) + 2);
}
``````

The third function calculates the final color value for a channel with hue and saturation.

``````double calc_sv(double i, double s, double v){
return s * v * (i - 1.0) + v;
}
``````

Finally, it's all put together:

``````void set_hsv_color(Color *c, double h, double s, double v){
double r, g, b;
r = calc_sv(calc_hue(h + ONE_THIRD), s, v);
g = calc_sv(calc_hue(h), s, v);
b = calc_sv(calc_hue(H - ONE_THIRD), s, v);
}
``````

In the final fucntion the input to the function `calc_hue` is offset foe each color channel because the math in `calc_hue` works out best for green but will work just fine for red and blue if shifted.

The full code can be found here.