从字节指针读取位的差异

Differences in reading bits from byte pointers

本文关键字:读取 字节 指针      更新时间:2023-10-16

我发现很难理解以下代码之间的差异:

auto pixel = static_cast<uint32_t>( D3DCOLOR_RGBA( r, g, b, a ) );
auto components = (uint8_t*)&pixel;
std::array<uint8_t, 4> pixel_colours = { components[0], components[1], components[2], components[3] };
uint8_t b_a = pixel >> 24;
uint8_t b_r = ( pixel >> 16 ) & 0xFF;
uint8_t b_g = ( pixel >> 8 ) & 0xFF;
uint8_t b_b = pixel & 0xFF;
return static_cast<uint32_t>( D3DCOLOR_RGBA( r, g, b, a ) );

对于 r, g, b, a = { 255, 128, 64, 0 },pixel_colours的值为{ 64, 128, 255, 0},而 b_a、b_r、b_g、b_b0, 255, 128, 64

我不明白为什么会发生差异 - 我希望它们是相同的。有人可以解释一下吗?

components[0]...components[1]以字节数组的形式访问内存,并按照内存中列出的顺序读取。pixel >> 24......pixel & 0xFF访问 int 的逻辑值。由于x86和x64(英特尔(架构使用小端序,因此两者有所不同。关于Endianess的Wiki文章解释了所有细节。