简体   繁体   English

在C ++中,这是否可以正确地将两个无符号的32位整数组合为一个无符号的64位整数?

[英]Does this correctly combine two unsigned 32-bit integers into one unsigned 64-bit integer in C++?

Does this correctly combine two unsigned 32-bit integers into one unsigned 64-bit integer in C++? 在C ++中,这是否可以正确地将两个无符号的32位整数组合为一个无符号的64位整数?

std::uint32_t a = ...
std::uint32_t b = ...
std::uint64_t result = ((std::uint64_t)a << 32) | (std::uint64_t)b) 

Is this code valid for all the unsigned integer values of a & b? 此代码对a和b的所有无符号整数值均有效吗?

Actually, I want unique result values for all possible unsigned integer values of a & b. 实际上,我想要a和b的所有可能的无符号整数值的唯一结果值。 The aim is to keep the size/length of the result minimal (in this case, we can bind it in 64 bit). 目的是使结果的大小/长度保持最小(在这种情况下,我们可以将其绑定到64位)。

是的,它可以按您期望的方式工作(如果它们确实是未签名的)。

Another method: 另一种方法:

uint32_t a = xxx;
uint32_t b = xxx;
uint64_t result;
uint32_t * p = (uint32_t *)&result;
p[0] = b;
p[1] = a;

Or maybe better: 也许更好:

union
{
  uint32_t b;
  uint32_t a;
  uint64_t res;
} u3264;
u3264 u;
u.a = xxx;
u.b = yyy;
// 64 bit result in u.res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM