如何将十六进制添加到字符数组

How to add hex to char array?

本文关键字:字符 数组 添加 十六进制      更新时间:2023-10-16

我已经编程了一段时间,但我对C++相当陌生。我正在编写一个程序,该程序采用.exe并获取其十六进制并将其存储在无符号字符数组中。我可以接受.exe并返回其十六进制罚款。我的问题是我在 char 数组中以正确的格式存储十六进制时遇到问题。

当我打印数组时,它会输出十六进制,但我需要在前面添加 0x。

示例输出:04 5F 4B F4 C5 A5
所需输出:0x04 0x5F 0x4B 0xF4 0xC5 0xA5

我正在尝试使用 hexcode[i] = ("0x%.2X", (unsigned char)c); 来正确存储它,但它似乎仍然只返回最后两个字符而没有 0x。

我也尝试了hexcode[i] = '0x' + (unsigned char)c;并研究了sprintf等功能。

谁能帮我获得想要的输出?甚至可能吗?

完整程序 -

    #include <iostream>
unsigned char hexcode[99999] = { 0 };
//Takes exes hex and place it into unsigned char array
int hexcoder(std::string file) {
    FILE *sf; //executable file
    int i, c;
    sf = fopen(file.c_str(), "rb");
    if (sf == NULL) {
        fprintf(stderr, "Could not open file.", file.c_str());
        return 1;
    }
    for (i = 0;;i++) {
        if ((c = fgetc(sf)) == EOF) break;
        hexcode[i] = ("0x%.2X", (unsigned char)c);
        //Print for debug
        std::cout << std::hex << static_cast<int>(hexcode[i]) << ' ';
    }
}
int main()
{
    std::string file = "shuffle.exe"; // test exe to pass to get hex
    hexcoder(file);
    system("pause");
    return 0;
}

我想你想转储一个十六进制格式的文件。所以也许它类似于您正在寻找的以下代码。请注意,hexcode更改为数据类型 char 而不是unsigned char,以便可以将其作为包含可打印字符的字符串进行处理。

int hexcoder(std::string file) {
    FILE *sf; //executable file
    int i, c;
    sf = fopen(file.c_str(), "rb");
    if (sf == NULL) {
        fprintf(stderr, "Could not open file %s.", file.c_str());
        return 1;
    }
    char hexcode[10000];
    char* wptr = hexcode;
    for (i = 0;;i++) {
        if ((c = fgetc(sf)) == EOF) break;
        wptr += sprintf(wptr,"0x%02X ", c);            
    }
    *wptr = 0;
    std::cout << hexcode;
    return 0;
}

顺便说一句:为了打印出十六进制格式的值,也可以使用...

printf("0x%2X ", c)

std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << std::uppercase << c << " ";

请注意,后者需要 #include <iomanip> .

但是 - 为了不过多地改变代码的语义 - 我将hexcode字符串保留为目标。