【问题标题】:Concatenating hex values in C++在 C++ 中连接十六进制值
【发布时间】:2015-10-29 20:34:20
【问题描述】:

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

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

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

【问题讨论】:

  • size_t 和 ptrdiff_t 是你想要的类型
  • mainMemory的类型是什么?
  • @AlanStokes 它是一个字符数组

标签: c++ hex bit-manipulation


【解决方案1】:

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

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

【讨论】:

  • 这是对 machine-&gt;mainMemory 类型的灵感猜测吗?
  • @Roddy:与其说是猜测不如说是基于证据的推论。
猜你喜欢
  • 2017-08-26
  • 1970-01-01
  • 2014-11-30
  • 2011-06-01
  • 2010-10-03
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
相关资源
最近更新 更多