如何将十六进制添加到字符数组
How to add hex to char array?
我已经编程了一段时间,但我对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
字符串保留为目标。
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?