转换RGB到十六进制C++?

cgh8pdjw  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(158)

我正在寻找一个简单的C++函数,它需要三个整数作为r,g和B,并返回相应的十六进制颜色代码作为整数。先谢谢你了!

p5cysglq

p5cysglq1#

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

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

h43kikqp

h43kikqp2#

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

假定r、g、B是无符号8位字符。
(That这真的很容易,Google会提供帮助。

brtdzjyr

brtdzjyr3#

我得到这个页面,因为我需要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();
}

相关问题