How to read bytes from file to hex string in C++?

Viewed 309

I am trying to read a file which contains bytes into a hex string.

std::ifstream infile("data.txt", std::ios_base::binary);

int length = 10;
char char_arr[length];
for (int i=0; i<length; i++)
{
     infile.get(char_arr[i]);
}
std::string hex_data(char_arr);

However the hex_data does not look like a hex string. Is there a way to convert the bytes to a hex string during reading?

2 Answers

You are reading in raw bytes and storing them as-is into your std::string. If you want the std::string to be hex formatted, you need to handle that formatting yourself, eg:

#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>

std::ifstream infile("data.txt", std::ios_base::binary);

const int length = 10;
unsigned char bytes[length];

if (infile.read(reinterpret_cast<char*>(bytes), length)) {
    size_t numRead = infile.gcount();
    std::ostringstream oss;
    for(size_t i = 0; i < numRead; ++i) {
        oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned short>(bytes[i]);
    }
    std::string hex_data = oss.str();
    ...
}

use std::stringstream object

std::stringstream stream;
stream << std::hex << static_cast<int>( your_char);
std::string result( stream.str() );
Related