在 C++ 中连接十六进制值

Concatenating hex values in C++

我在用 C++ 连接两个十六进制值时遇到问题;

int virtAddr = (machine->mainMemory[ptrPhysicalAddr + 1] << 8) | (machine->mainMemory[ptrPhysicalAddr]);
int physAddr = currentThread->space->GetPhysicalAddress(virtAddr);

对于 machine->mainMemory[ptrPhysicalAddr + 1],这会产生 0x5。对于 machine->mainMemory[ptrPhysicalAddr],这会产生 0x84。我期待结果 0x584。但是,我得到 0xffffff84。我关注了这个问题Concatenate hex numbers in C

0x84 是 -124。它在按位或运算(整数提升)之前扩大到 (int)-1240x00000500 | 0xFFFFFF84 是你得到的结果。在加宽时使用无符号类型以防止符号扩展。

intptr_t virtAddr = (uint8_t(machine->mainMemory[ptrPhysicalAddr + 1]) << 8)
                   | uint8_t(machine->mainMemory[ptrPhysicalAddr]);