#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();
}
3条答案
按热度按时间p5cysglq1#
当然,您需要一些输出格式来将其显示为十六进制。
h43kikqp2#
假定r、g、B是无符号8位字符。
(That这真的很容易,Google会提供帮助。
brtdzjyr3#
我得到这个页面,因为我需要R,G,B转换为一个有效的十六进制字符串(* 十六进制颜色代码 )在HTML文档中使用。我花了一些时间才把它做好,所以把它放在这里作为其他人( 和我未来的自己 *)的参考。