rightaway717
rightaway717

Reputation: 2841

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

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).

I'd appreciate your help.

Upvotes: 3

Views: 1419

Answers (1)

user268396
user268396

Reputation: 12006

The warning has to do with the size of si32 itself. Basically the sequence of steps looks like this:

  1. Take si32 (which is a 32bit value)
  2. Shift that value by 32bits (i.e. shift a 32bit value by 32 bits)
  3. Assign it to 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:

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

Upvotes: 7

Related Questions