Reputation: 31
I am looking for a simple C++ function that takes three integers as r, g, and b and returns the corresponding hex color code as an integer. Thanks in advance!
Upvotes: 1
Views: 5061
Reputation: 807
I got on this page because I needed R, G, B converted to a valid Hex string (Hex color code) for use within an HTML document. It took me some time to get it right, so putting it here as reference for others (and my future self).
#include <sstream>
#include <iomanip>
//unsigned char signature ensures that any input above 255 gets automatically truncated to be between 0 and 255 appropriately (e.g. 256 becomes 0)
std::string rgbToHex(unsigned char r, unsigned char g, unsigned char b) {
std::stringstream hexSS;
std::stringstream outSS;
//setw(6) is setting the width of hexSS as 6 characters. setfill('0') fills any empty characters with 0. std::hex is setting the format of the stream as hexadecimal
hexSS << std::setfill('0') << std::setw(6) << std::hex;
//r<<16 left shifts r value by 16 bits. For the complete expression first 8 bits are represented by r, then next 8 by g, and last 8 by b.
hexSS << (r<<16 | g<<8 | b);
outSS << "#" << hexSS.str();
return outSS.str();
}
Upvotes: 0
Reputation: 308111
int hexcolor(int r, int g, int b)
{
return (r<<16) | (g<<8) | b;
}
Of course you'll need some output formatting to show it as hex.
Upvotes: 2
Reputation: 11414
unsigned long rgb = (r<<16)|(g<<8)|b;
given that r,g,b are unsigned 8bit chars.
(That´s really easy, and Google would´ve helped.)
Upvotes: 0