简体   繁体   English

C ++说明将uint64强制转换为uint32

[英]C++ explain casting uint64 to uint32

I'm trying to cast a uint64_t (representing time in nanoseconds from D-day using a boost chrono high precision clock) to a uint32_t in order to seed a random number generator. 我正在尝试将uint64_t(使用升压计时高精度时钟表示从D天开始的纳秒级时间)转换为uint32_t,以播种随机数生成器。

I just want the least significant 32 bits of the uint64_t. 我只想要uint64_t的最低有效32位。 Here is my attempt: 这是我的尝试:

uint64_t ticks64 = dtn.count(); // This has the ticks in nanosec
uint64_t ticks32_manual = ticks64 & 0xFFFFFFFF;
uint32_t ticks32_auto = (uint32_t) ticks64;
mexPrintf("Periods: %llu\n", ticks64);
mexPrintf("32-bit manual truncation: %llu\n", ticks32_manual);
mexPrintf("32-bit automatic truncation: %u\n", ticks32_auto);

The output of my code is as follows: 我的代码输出如下:

Periods: 651444791362198 期间:651444791362198

32-bit manual truncation: 1331774102 32位手动截断:1331774102

32-bit automatic truncation: 1331774102 32位自动截断:1331774102

I was expecting the last few digits of the 32 and original 64-bit representations to be the same, but they are not. 我期望32位和原始64位表示形式的最后几位相同,但事实并非如此。 That is, I thought I would "lose the left half" of the 64-bit number. 也就是说,我以为我会“丢失” 64位数字的左半部分。

Can anyone explain what's going on here? 谁能解释这是怎么回事? Thanks. 谢谢。

Btw, I've seen this link . 顺便说一句,我看过这个链接

As pointed out in the comments there's nothing wrong with the operation of your code, it's just that you're not visualizing the output correctly. 正如注释中指出的那样,代码的操作没有任何问题,只是您没有正确地可视化输出。 Here's your code, corrected and runnable: 这是您的已更正且可运行的代码:

#include <cstdio>
#include <cstdint>

int main() {
  uint64_t ticks64 = 651444791362198llu;
  uint64_t ticks32_manual = ticks64 & 0xFFFFFFFF;
  uint32_t ticks32_auto = (uint32_t) ticks64;

  printf("Periods: %llX\n", ticks64);
  printf("32-bit manual truncation: %llX\n", ticks32_manual);
  printf("32-bit automatic truncation: %X\n", ticks32_auto);
}

And the output is: 输出为:

Periods: 2507C4F614296
32-bit manual truncation: 4F614296
32-bit automatic truncation: 4F614296

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

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