如何从一个long long int中提取四个unsigned short int?

Paw*_*dan 5 c c++ 64-bit bit-manipulation

假设我有一个long long int并且想要取其位并构造四个无符号短整数.

特别顺序在这里并不重要.

我通常知道我需要将位移位并截断为unsigned short int的大小.但我想我可能会在某个地方犯一些奇怪的错误,所以我问.

Chr*_*ung 11

#include <stdint.h>
#include <stdio.h>

union ui64 {
    uint64_t one;
    uint16_t four[4];
};

int
main()
{
    union ui64 number = {0x123456789abcdef0};
    printf("%x %x %x %x\n", number.four[0], number.four[1],
                            number.four[2], number.four[3]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)