简体   繁体   中英

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

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?

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() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM