简体   繁体   English

如何在C ++中将RGB颜色值转换为十六进制值?

[英]how to convert a RGB color value to an hexadecimal value in C++?

In my C++ application, I have a png image's color in terms of Red, Green, Blue values. 在我的C ++应用程序中,我用红色,绿色和蓝色值表示png图像的颜色。 I have stored these values in three integers. 我将这些值存储在三个整数中。

How to convert RGB values into the equivalent hexadecimal value? 如何将RGB值转换为等效的十六进制值?

Example of that like in this format 0x1906 这种格式的示例0x1906

EDIT: I will save the format as GLuint. 编辑:我将格式保存为GLuint。

Store the appropriate bits of each color into an unsigned integer of at least 24 bits (like a long ): 将每种颜色的适当位存储为至少24位(如long )的无符号整数:

unsigned long createRGB(int r, int g, int b)
{   
    return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
}

Now instead of: 现在代替:

unsigned long rgb = 0xFA09CA;

you can do: 你可以做:

unsigned long rgb = createRGB(0xFA, 0x09, 0xCA);

Note that the above will not deal with the alpha channel. 请注意,以上内容不涉及Alpha通道。 If you need to also encode alpha (RGBA), then you need this instead: 如果您还需要编码alpha(RGBA),则需要以下代码:

unsigned long createRGBA(int r, int g, int b, int a)
{   
    return ((r & 0xff) << 24) + ((g & 0xff) << 16) + ((b & 0xff) << 8)
           + (a & 0xff);
}

Replace unsigned long with GLuint if that's what you need. 如果需要,请用GLuint替换unsigned long

If you want to build a string, you can probably use snprintf() : 如果要构建字符串,则可以使用snprintf()

const unsigned red = 0, green = 0x19, blue = 0x06;
char hexcol[16];

snprintf(hexcol, sizeof hexcol, "%02x%02x%02x", red, green, blue);

This will build the string 001906" in hexcol`, which is how I chose to interpret your example color (which is only four digits when it should be six). 这将001906" in hexcol`中构建字符串001906" in ,这就是我选择解释示例颜色的方式(当颜色应为6时只有4位)。

You seem to be confused over the fact that the GL_ALPHA preprocessor symbol is defined to be 0x1906 in OpenGL's header files. 您似乎对GL_ALPHA预处理器符号在OpenGL的头文件中定义为0x1906的事实感到困惑。 This is not a color, it's a format specifier used with OpenGL API calls that deal with pixels, so they know what format to expect. 这不是颜色,它是用于处理像素的OpenGL API调用使用的格式说明符 ,因此他们知道期望的格式。

If you have a PNG image in memory, the GL_ALPHA format would correspond to only the alpha values in the image (if present), the above is something totally different since it builds a string. 如果内存中有PNG图像,则GL_ALPHA格式将与图像中的alpha值(如果存在)相对应,上述内容完全不同,因为它会生成字符串。 OpenGL won't need a string, it will need an in-memory buffer holding the data in the format required. OpenGL不需要字符串,而是需要一个内存中的缓冲区来保存所需格式的数据。

See the glTexImage2D() manual page for a discussion on how this works. 请参阅glTexImage2D()手册页以获取有关其工作原理的讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM