如何将4个int(范围0..255)转换为uint32_t

时间:2019-02-10 15:40:00

标签: c++

我有4个整数,int r = 255g = 255b = 255a = 255。我想将它们转换为uint32_t

uint32_t c = 0xFFFFFFFF;

以一种方式

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

这需要字节操作吗?

1 个答案:

答案 0 :(得分:0)

以下是几种不同的方式:

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);