将 RGB 转换为十六进制C++

Convert RGB to Hex C++?

本文关键字:十六进制 C++ 转换 RGB      更新时间:2023-10-16

我正在寻找一个简单的C++函数,它将三个整数作为r,g和b,并将相应的十六进制颜色代码作为整数返回。提前感谢!

int hexcolor(int r, int g, int b)
{
    return (r<<16) | (g<<8) | b;
}

当然,您需要一些输出格式才能将其显示为十六进制。

unsigned long rgb = (r<<16)|(g<<8)|b; 

鉴于 R,G,B 是无符号的 8 位字符。
(这真的很容易,谷歌会提供帮助。

我进入这个页面是因为我需要将 R、G、B 转换为有效的十六进制字符串(十六进制颜色代码)以在 HTML 文档中使用。我花了一些时间才把它做好,所以把它放在这里作为别人(和我未来的自己)的参考。

#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();
}