c++ - 将字符数组转换为整数值

标签 c++ binary hex portable-executable

我在计算 WORD、DWORD 等的正确计算时遇到了一些麻烦。 我脑子里有个疙瘩,可能是在这个问题上坐了太久了。

我正在阅读 PE 部分标题。到目前为止一切正常。 以下是随机 .exe 文件的示例输出:

File is 286 Kbytes large
PE-Signature [@ 0x108]
0x00000100: ........ ........ 504500

Collect Information (PE file header):
[WORD]  Mashinae Type          :014C
[WORD]  Number of Sections     :0006
[DWORD] TimeStamp              :5C6ECB00
[DWORD] Pointer to symbol table:00000000
[DWORD] Number of Symbols      :00000000
[WORD]  Size of optional header:00E0

现在,如您所见,“可选” header 的大小为 0x00E0,所以我试图缓冲它以备后用。 (公元前。只阅读完整的标题会使事情变得更快)。

我遇到问题的地方是我要将小端值转换为实际整数。 我需要从后面读取值(因此第二个 WORD [00] 实际上是要读取的第一个值)。 然而,第二个值需要以某种方式移动(bc。字节的重要性),这就是我挣扎的地方。我想解决方案并没有那么难,我只是没有智慧了,哈哈。

这是我的函数草稿,它应该返回一个整数值:

 //get a specific value and safe it for later usage
 int getValue(char* memory, int start, int end)
 {
   if (end <= start)
       return 0;

   unsigned int retVal = 0;

   //now just add up array fields 
   for (int i = end; i >= start; i--)
   {
       fprintf(stdout, "\n%02hhx", memory[i]);
       retVal &= (memory[i] << 8 * (i- start));
   }
   fprintf(stdout, "\n\n\n%d",retVal);

   return retVal;
}

换句话说,我需要将十六进制值(或字符)数组解析为实际整数,但要考虑字节的重要性。

还有: [指向符号表的指针] 和 [符号数] 似乎始终为 0。我猜这是因为二进制文件中的符号被剥离了,但我不确定,因为我是 Linux 二进制方面的专家分析。我的假设是否正确?

最佳答案

希望对您有所帮助。据我目前的理解,这将获取从开始到结束范围内的字节,并将它们放在一个整数中:

// here I am converting the chars from hex to int
int getBitPattern(char ch)
{
    if (ch >= 48 && ch <= 57)
    {
        return ch - '0';
    }
    else if (ch >= 65 && ch <= 70)
    {
        return ch - 55;
    }
    else
    {
        // this is in case of invalid input
        return -1;
    }
}


int getValue(const char* memory, int start, int end)
{
    if (end <= start)
        return 0;

    unsigned int retVal = 0;

    //now just add up array fields 
    for (int i = end, j = 0; i >= start; i--, ++j)
    {
        fprintf(stdout, "\n%02hhx", memory[i]);
        // bitshift in order to insert the next set of 4 bits into their correct spot
        retVal |= (getBitPattern(memory[i]) << (4*j));
    }
    fprintf(stdout, "\n\n\n%d", retVal);
    return retVal;
}

关于c++ - 将字符数组转换为整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59219415/

相关文章:

c++ - 如何通过按 "cancel"键取消 CListCtrl 中的编辑?

C++ 赋值与删除的赋值运算符一起使用?

python - 装饰十六进制函数以填充零

php - 获取 html 实体的十六进制代码

c++ - 是否优化了空基虚拟方法?

c++ - 为什么 reinterpret_cast 不强制 copy_n 用于相同大小类型之间的转换?

c - 如何使用 fread() 读取二进制文件

json - 基于 Protocol Buffer (protobufs)/二进制与 JSON/文本性能的 Websockets

python - 十六进制正则表达式字符串匹配不起作用(python)

android - QtCreator 甚至无法构建空项目 - 执行此行时发生以下错误