1

I am having trouble concatenating two hex values in C++;

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

For machine->mainMemory[ptrPhysicalAddr + 1], this yields 0x5. For machine->mainMemory[ptrPhysicalAddr], this yields 0x84. I expect the result 0x584. However, I am getting 0xffffff84. I followed this question Concatenate hex numbers in C.

Cœur
  • 37,241
  • 25
  • 195
  • 267
mrQWERTY
  • 4,039
  • 13
  • 43
  • 91

1 Answers1

4

0x84 is -124. It gets widened to (int)-124 before the bitwise-OR operation (integer promotion). And 0x00000500 | 0xFFFFFF84 is the result you got. Use an unsigned type to prevent sign-extension when widening.

intptr_t virtAddr = (uint8_t(machine->mainMemory[ptrPhysicalAddr + 1]) << 8)
                   | uint8_t(machine->mainMemory[ptrPhysicalAddr]);
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720