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
  • 34,719
  • 24
  • 185
  • 251
mrQWERTY
  • 3,699
  • 11
  • 37
  • 90

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
  • 269,602
  • 39
  • 394
  • 697