Alex Deroza
Alex Deroza

Reputation: 15

Can't correctly shift my values on uint64?

I can't understand how I can shift bits correctly in my C++ code:

uint64 iSteamId = FCString::Atoi(*gz_pid);

uint8 UniverseAccount = (iSteamId << 56) & 0xFF; // X
uint8 LowestBit = (iSteamId >> 63) & 0xFF; // Y
uint32 AccountNumber = (iSteamId << 32) & 0x7FFFFFF; // Z

gz_SteamId += "STEAM_" + \
    FString::FromInt(UniverseAccount) + ":" + \
    FString::FromInt(LowestBit) + ":" + \
    FString::FromInt(AccountNumber);

The image shows how you can read some recommendations from Steam how it must be done:

steam wiki recommendations

Upvotes: 0

Views: 259

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409206

You seem to be misunderstanding how bits and shift work in C++.

To begin: The lowest (least significant) bit is number 0. On a 64-bit number the highest (most significant) bit is number 63.

Shifting to the right moves high bits to the lower positions, filling up with zero bits at the top. Shifting to the left move bits to the higher positions, filling up with zero bits at the bottom.

If you have the byte 0b1000000 (decimal 128) and shift it one position to the right (with >>) you get 0b01000000 (decimal 64).

If you have the byte 0b00000001 (decimal 1) and shift it one position to the left (with <<) you get 0b00000010 (decimal 2).


For your problem:

The lowest bit doesn't need any shift to be had, it's always the lowest bit which you get with e.g. iSteamId & 1.

The next 31 bits you shift down one bit to remove the lowest bit, and mask with the the 31 lowest bits: (iSteamId >> 1) & 0x7fffffff.

For the top eight bits you shift down 56 bits and just let the compiler truncate the result: iSteamId >> 56.

These shifts assumes Intel little-endian system.

Upvotes: 3

Related Questions