Bushido said:
Hey c.l.c++ and/or c.g.a.opengl posters,
How do I convert a hexidecimal string, traditionally used for defining
colors with HTML, into a floating point array?
In other words, how do I convert this:
char* hex = "#FF9933";
into this:
float fpa = { 1.0, 0.6, 0.2 };
Here's a couple of example methods:
// hex2rgb.cpp - test some hex to RGB color conversion
// methods.
// compile: g++ -o hex2rgb hex2rgb.cpp
// execute: ./hex2rgb some_hex_string
#include <cstdlib> // for strtoul()
#include <iostream>
// convert a hex color string to three integer RGB values.
// returns zero on success, non-zero on error.
int
hex2rgb(const char * hex, int& red, int& green, int& blue)
{
unsigned long val;
if (NULL == hex)
{
red = green = blue = 0;
return 1;
}
// convert the hex string to an unsigned long int.
// val will be zero if 'hex' is invalid.
// Note: we should check 'errno' after this call
// to see if a conversion error occurred;
// see the docs for strtoul().
val = strtoul(hex, NULL, 16);
red = ((val & 0xff0000) >> 16);
green = ((val & 0xff00) >> 8);
blue = (val & 0xff);
return 0;
}
// convert a hex color string to three float RGB values.
// returns zero on success, non-zero on error.
// Note this is the same as the int version except we
// divide each derived RGB color by 255.0. this method
// could simply call the int version then divide those
// results by 255.0 before returning
int
hex2rgb(const char * hex, float& red, float& green, float& blue)
{
unsigned long val;
if (NULL == hex)
{
red = green = blue = 0.0;
return 1;
}
// convert the hex string to an unsigned long int.
// val will be zero if 'hex' is invalid.
// Note: we should check 'errno' after this call
// to see if a conversion error occurred;
// see the man page for strtoul(),
val = strtoul(hex, NULL, 16);
red = ((float)((val & 0xff0000) >> 16)) / 255.0;
green = ((float)((val & 0xff00) >> 8)) / 255.0;
blue = ((float)(val & 0xff)) / 255.0;
return 0;
}
int
main(int argc, char * argv[])
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " hex_value" << std::endl;
return 1;
}
int ir, ig, ib;
float fr, fg, fb;
// get the int RGB values into ir, ig, and ib
hex2rgb(argv[1], ir, ig, ib);
std::cout << argv[1] << ": red = " << ir << " green = " << ig
<< " blue = " << ib << std::endl;
// get the float RGB values into fr, fg, and fb
hex2rgb(argv[1], fr, fg, fb);
std::cout << argv[1] << ": red = " << fr << " green = " << fg
<< " blue = " << fb << std::endl;
return 0;
}
Regards,
Larry