我有4个整数,int r = 255
,g = 255
,b = 255
和a = 255
。我想将它们转换为uint32_t
。
uint32_t c = 0xFFFFFFFF;
以一种方式
uint32_t c = 0x(int)r(int)g(int)b(int)a;
这需要字节操作吗?
答案 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);