How to convert 4 ints (range 0..255) to uint32_t

-1

I have 4 ints, int r = 255, g = 255, b = 255 and a = 255. I would like to convert them to uint32_t.

uint32_t c = 0xFFFFFFFF;

in a manner

uint32_t c = 0x(int)r(int)g(int)b(int)a;

Does this require byte operations?

c++
asked on Stack Overflow Feb 10, 2019 by Konsta Gogoduck • edited Feb 10, 2019 by Raymond Chen

1 Answer

0

Here are a couple different ways:

unsigned long c =
    ((static_cast<unsigned long>(r) & 0xFF) << 24) |
    ((static_cast<unsigned long>(g) & 0xFF) << 16) |
    ((static_cast<unsigned long>(b) & 0xFF) <<  8) |
    ((static_cast<unsigned long>(a) & 0xFF) <<  0);

unsigned long d;
unsigned char *pd = reinterpret_cast<unsigned char *>(&d);

// only works on little-endian CPUs

*pd++ = static_cast<unsigned char>(a);
*pd++ = static_cast<unsigned char>(b);
*pd++ = static_cast<unsigned char>(g);
*pd++ = static_cast<unsigned char>(r);
answered on Stack Overflow Feb 10, 2019 by spongyryno

User contributions licensed under CC BY-SA 3.0