将二进制文件转换为十六进制表示法 [英] Convert binary file to hex notation
问题描述
我想为我在参数中输入的二进制文件获取此十六进制表示法:
I would like to obtain this hex notation for a binary I enter in parameter:
我获得的输出以及我想要的东西
The output I obtain and what I want:
这是我编写的代码,我没有好的十六进制数字(对于5A之后的部分),我做错了什么?如何正确地将我读取的字节转换为十六进制? 谢谢.
This is the code I written, I don't have the good hex number (for the part after 5A) , what I am doing wrong ? How to convert properly the byte I read to hex ? Thanks.
int main(int argc, char *argv[])
{
std::string parameter = "The\\Path\\To\My\exe.exe";
ifstream::pos_type size;
char * memblock;
ifstream file(parametre, ios::in | ios::binary | ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char[size];
file.seekg(0, ios::beg);
file.read(memblock, size);
file.close();
cout << "the complete file content is in memory" << endl;
string str = string(memblock, size);
string hexContent = "";
int maxColumn = 0;
std::stringstream ss;
int column = 0;
for (int i = 0; i < size; ++i)
{
ss << std::hex << (int)str[i];
if (column == 8)
{
ss << '\n';
column = 0;
}
column++;
}
std::string mystr = ss.str();
cout << mystr;
}
return 0;
}
推荐答案
看起来像char
在您的系统上签名,并且您是符号扩展名的受害者.例如0x90是负数,因此当将其转换为int
时,必须进行负运算,结果为0xffffff90.
Looks like char
is signed on your system and you are the victim of sign extension. For example 0x90 is a negative, so when it's converted into an int
, that negativity has to be carried through, resulting in 0xffffff90.
将文件读取到unsigned char
,如果可用,则从<cstdint>
读取uint8_t
,而不是char
的数组.
Read the file into unsigned char
, or uint8_t
from <cstdint>
if it is available, instead of an array of char
.
char * memblock;
成为
uint8_t * memblock;
然后
memblock = new char[size];
成为
memblock = new uint8_t[size];
,以后不要将其转换为string
.
and don't convert it into a string
later.
string str = string(memblock, size);
是没有意义的,您可以很容易地从memblock
中读取内容,并撤消我们之前建立的无符号性.只需从memblock
is pointless, you could just as easily have read from memblock
, and undoes the unsigned-ness we've established earlier. Just read out of memblock
别忘了
delete[] memblock;
完成后.导致
使用std::vector
.它会自行清理.
std::vector<uint8_t> memblock(size);
file.seekg(0, ios::beg);
file.read(reinterpret_cast<char*>(memblock.data()), size);
//or file.read(reinterpret_cast<char*>(&memblock[0]), size); if no or data method
这篇关于将二进制文件转换为十六进制表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!