C++ 如何将一个 64 位整数存储在两个 32 位整数中并再次转换回来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2810280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store a 64 bit integer in two 32 bit integers and convert back again
提问by Stowelly
I'm pretty sure its just a matter of some bitwise operations, I'm just not entirely sure of exactly what I should be doing, and all searches return back "64 bit vs 32 bit".
我很确定这只是一些按位运算的问题,我只是不完全确定我应该做什么,并且所有搜索都返回“64 位 vs 32 位”。
回答by Hyman
pack:
盒:
u32 x, y;
u64 v = ((u64)x) << 32 | y;
unpack:
解压:
x = (u32)((v & 0xFFFFFFFF00000000LL) >> 32);
y = (u32)(v & 0xFFFFFFFFLL);
回答by lhf
Or this, if you're not interested in what the two 32-bits numbers mean:
或者,如果您对两个 32 位数字的含义不感兴趣:
u32 x[2];
u64 z;
memcpy(x,&z,sizeof(z));
memcpy(&z,x,sizeof(z));
回答by Viktor Sehr
Use a unionand get rid of the bit-operations:
使用联合并摆脱位操作:
<stdint.h> // for int32_t, int64_t
union {
int64_t big;
struct {
int32_t x;
int32_t y;
};
};
assert(&y == &x + sizeof(x));
simple as that. big consists of both x and y.
就那么简单。big 由 x 和 y 组成。
回答by aphax
I don't know if this is any better than the union or memcpy solutions, but I had to unpack/pack signed64bit integers and didn't really want to mask or shift anything, so I ended up simply treating the 64bit value as two 32bit values and assign them directly like so:
我不知道这是否比 union 或 memcpy 解决方案更好,但我不得不解包/打包带符号的64 位整数,并且不想屏蔽或移动任何东西,所以我最终只是将 64 位值视为两个32位值并直接分配它们,如下所示:
#include <stdio.h>
#include <stdint.h>
void repack(int64_t in)
{
int32_t a, b;
printf("input: %016llx\n", (long long int) in);
a = ((int32_t *) &in)[0];
b = ((int32_t *) &in)[1];
printf("unpacked: %08x %08x\n", b, a);
((int32_t *) &in)[0] = a;
((int32_t *) &in)[1] = b;
printf("repacked: %016llx\n\n", (long long int) in);
}
回答by Williham Totland
The basic method is as follows:
基本方法如下:
uint64_t int64;
uint32_t int32_1, int32_2;
int32_1 = int64 & 0xFFFFFFFF;
int32_2 = (int64 & (0xFFFFFFFF << 32) ) >> 32;
// ...
int64 = int32_1 | (int32_2 << 32);
Note that your integers must be unsigned; or the operations are undefined.
请注意,您的整数必须是无符号的;或者操作未定义。
回答by Sajjad Behravesh
long x = 0xFEDCBA9876543210;
cout << hex << "0x" << x << endl;
int a = x ;
cout << hex << "0x" << a << endl;
int b = (x >> 32);
cout << hex << "0x" << b << endl;