简体   繁体   English

如何将32位有符号整数放入64位无符号整数的高32位?

[英]How to put 32-bit signed integer into higher 32 bits of 64-bit unsigned integer?

Example: 例:

qint32 si32 = -1; // that gives us 0xFFFFFFFF
quint64 ui64 = si32; // that gives us 0xFFFFFFFFFFFFFFFF, that is expected

Desired result: 期望的结果:

0xFFFFFFFF00000000

When I'm trying to shift bits on si32 like this 当我试图像这样在si32上移位时

quint64 ui64 = si32 << 32;

compiler warns me about bit-shifting overflow. 编译器警告我有关位移溢出的信息。

That should be an easy task, but I can't figure out how to do that. 这应该是一项简单的任务,但我无法弄清楚如何做到这一点。 That is a unix C++ code (using QT, but that doesn't matter, plain unix C++ code will do). 这是一个unix C ++代码(使用QT,但这没关系,普通的unix C ++代码会这样做)。

I'd appreciate your help. 我很感激你的帮助。

The warning has to do with the size of si32 itself. 警告与si32本身的大小有关。 Basically the sequence of steps looks like this: 基本上步骤的顺序如下:

  1. Take si32 (which is a 32bit value) si32 (32位值)
  2. Shift that value by 32bits (ie shift a 32bit value by 32 bits) 将该值移位32位(即将32位值移位32位)
  3. Assign it to ui64 . 将其分配给ui64

To fix that, you can first cast si32 to the proper 64bit type, before shifting it by 32 bits so the bit shifting will operate on 64bit values: 要解决此问题,您可以先将si32转换为正确的64位类型,然后再将其移位32位,这样位移位将在64位值上运行:

quint64 ui64 = ((quint64) si32) << 32;

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

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