C++ read binary file and convert to hex -


i'm having problems reading binary file , converting it's bytes hex representation.

what i've tried 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 in memory" << endl;  std::string tohexed = tohex(memblock, true);       std::cout << tohexed << std::endl;     } 

converting hex:

string tohex(const string& s, bool upper_case) {     ostringstream ret;      (string::size_type = 0; < 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 open original file hex editor, 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 way 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;      (string::size_type = 0; < 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(); } 

char *memblock; …  std::string tohexed = tohex(memblock, true); …  string tohex(const string& s, bool upper_case) 

there's problem, right there. constructor std::string::string(const char*) interprets input nul-terminated string. so, characters leading '\0' passed tohex. try 1 of these instead:

std::string tohexed = tohex(std::string(memblock, memblock+size), true); std::string tohexed = tohex(std::string(memblock, size), true); 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -