从字节指针读取位的差异

时间:2017-08-01 05:09:53

标签: c++ pointers

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

    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_b为0, 255, 128, 64

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

1 个答案:

答案 0 :(得分:3)

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