简体   繁体   English

在C ++中串联十六进制值

[英]Concatenating hex values in C++

I am having trouble concatenating two hex values in C++; 我在连接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 . 对于machine->mainMemory[ptrPhysicalAddr + 1] ,将产生0x5 For machine->mainMemory[ptrPhysicalAddr] , this yields 0x84 . 对于machine->mainMemory[ptrPhysicalAddr] ,将产生0x84 I expect the result 0x584 . 我期望结果为0x584 However, I am getting 0xffffff84 . 但是,我得到0xffffff84 I followed this question Concatenate hex numbers in C . 我遵循了这个问题,将C中的十六进制数字连接起来

0x84 is -124 . 0x84是-124 It gets widened to (int)-124 before the bitwise-OR operation (integer promotion). 在按位或运算(整数提升)之前,它会扩大到(int)-124 And 0x00000500 | 0xFFFFFF84 0x00000500 | 0xFFFFFF84 0x00000500 | 0xFFFFFF84 is the result you got. 结果是0x00000500 | 0xFFFFFF84 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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM