【发布时间】:2010-09-13 23:25:55
【问题描述】:
假设我有一个 long long int 并且想要取出它的位并从中构造四个 unsigned short int。
在这里,特定的顺序并不重要。
我通常知道我需要移位并截断到 unsigned short int 的大小。但我想我可能会在某个地方犯一些奇怪的错误,所以我问。
【问题讨论】:
标签: c++ c 64-bit bit-manipulation
假设我有一个 long long int 并且想要取出它的位并从中构造四个 unsigned short int。
在这里,特定的顺序并不重要。
我通常知道我需要移位并截断到 unsigned short int 的大小。但我想我可能会在某个地方犯一些奇怪的错误,所以我问。
【问题讨论】:
标签: c++ c 64-bit bit-manipulation
#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;
}
【讨论】:
union LongLongIntToThreeUnsignedShorts {
long long int long_long_int;
unsigned short int short_ints[sizeof(long long int) / sizeof(short int)];
};
这应该可以满足您的想法,而不必乱动位移。
【讨论】:
unsigned short int (可能每个 2 个字节 - 没关系)。我的观点是,除非您确定填充/对齐规则,否则该结构很危险。
(unsigned short)((((unsigned long long int)value)>>(x))&(0xFFFF))
其中value 是您的long long int,x 是四条短裤的 0、16、32 或 48。
【讨论】: