How to convert RGB color value to hex value in C ++?

In my C ++ application, I have the color of the png image in terms of the values ​​of red, green, blue. I saved these values ​​in three integers.

How to convert RGB values ​​to equivalent hex value?

An example of how in this format 0x1906

EDIT: I will save the format as GLuint.

+7
source share
2 answers

Store the corresponding bits of each color in an unsigned integer of at least 24 bits (e.g. 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); 

Please note that the above will not concern the alpha channel. If you need to encode alpha (RGBA) as well, then you need it:

 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 you need it.

+17
source

If you want to build a string, you can use snprintf() :

 const unsigned red = 0, green = 0x19, blue = 0x06; char hexcol[16]; snprintf(hexcol, sizeof hexcol, "%02x%02x%02x", red, green, blue); 

This will lead to the construction of line 001906" in hexcol`, so I decided to interpret your approximate color (these are just four digits, when there should be six).

You seem confused by the fact that the GL_ALPHA preprocessor GL_ALPHA is defined as 0x1906 in OpenGL header files. This is not a color, it is a format specifier used with OpenGL API calls that deal with pixels, so they know what format to expect.

If you have a PNG image in memory, the GL_ALPHA format will correspond only to the alpha values ​​in the image (if any), then this is completely different, since it builds a string. OpenGL does not need a string, for this you need a buffer in memory containing data in the desired format.

See the glTexImage2D() man page for a discussion of how this works.

+7
source

All Articles