将 RGB 转换为十六进制C++
Convert RGB to Hex C++?
我正在寻找一个简单的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();
}
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 指向存储在字符串 c++ 中的十六进制
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 绝对编码器十六进制输入
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- C++17 十六进制浮点文字单精度后缀冲突?
- 是否可以在C++中获取 CHAR 的有效十六进制地址?
- 打印十六进制字符
- 编译器始终打印十六进制/八进制数字