0

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?

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • 2
    `Does this require byte operations?` Bit operations? Yes, it does. Is that the question? – DeiDei Feb 10 '19 at 15:41
  • Welcome to Stack Overflow. We might be able to answer your question more sharply if you posted a *brief* code to show what you had tried. – thb Feb 10 '19 at 15:42
  • 1
    `#define U(x, y) ((static_cast(x & 0xFF) << y)` and `uint32_t c = U(r, 24) | U(g, 16) | U(b, 8) | U(a, 0);` followed by `#undef U`. – Eljay Feb 10 '19 at 15:42
  • 2
    @Eljay Would it not be preferable to avoid preprocessing macros in C++? – thb Feb 10 '19 at 15:44
  • True. An inline function or possibly a lambda could be used instead, to the same effect. – Eljay Feb 10 '19 at 16:13

1 Answers1

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);
spongyryno
  • 446
  • 2
  • 12