I'm having some problems reading a binary file and converting it's bytes to hex representation.
What I've tried so far:
ifstream::pos_type size;
char * memblock;
ifstream file (toread, 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;
std::string tohexed = ToHex(memblock, true);
std::cout << tohexed << std::endl;
}
Converting to hex:
string ToHex(const string& s, bool upper_case)
{
ostringstream ret;
for (string::size_type i = 0; i < s.length(); ++i)
ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];
return ret.str();
}
Result: 53514C69746520666F726D61742033
.
When I open the original file with a hex editor, this is what it shows:
53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00
04 00 01 01 00 40 20 20 00 00 05 A3 00 00 00 47
00 00 00 2E 00 00 00 3B 00 00 00 04 00 00 00 01
00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 A3
00 2D E2 1E 0D 03 FC 00 06 01 80 00 03 6C 03 D3
Is there a way to get the same desired output using C++?
Working solution (by Rob):
...
std::string tohexed = ToHex(std::string(memblock, size), true);
...
string ToHex(const string& s, bool upper_case)
{
ostringstream ret;
for (string::size_type i = 0; i < s.length(); ++i)
{
int z = s[i]&0xff;
ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << z;
}
return ret.str();
}
memblock
. I suspect thatmemblock
contains the entire file, but that the code you aren't showing us misinterprets its contents. Please reduce your program to the smallest complete program that demonstrates the error, and post that program in the question. sscce.org – Destefanowhile
loop, (2) callingtellg()
on a stream that you have just opened is premature. – Ceratedsize
isn't 15 bytes, just by pure coincidence being the count before the first null byte?ifstream
in binary mode certainly isn't supposed to do anything with null bytes... – Billyebilobate