Writing a hex file to a C ++ file

So, I know that this question has been asked many times. I apologize for the repeated task, but I did not ask any questions asked earlier, with my specific circumstances.

So, I have a program that reads a hex file, modifies it and saves the modified hex to std :: string. So for example, how can I write this to a file

std::string wut="b6306edf953a6ac8d17d70bda3e93f2a3816eac333d1ac78";

and get its value

.0n..:j..}p...?*8...3..x

in the output file?

I would prefer not to use sprintf, but I think if necessary, I will do what I should.

Thanks everyone ~ P

+3
source share
2 answers

, , , . , , , byte by byte. . .

#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <ios>

std::string wut = "b6306edf953a6ac8d17d70bda3e93f2a3816eac333d1ac78";

int main()
{
    std::ofstream datafile("c:\\temp\\temp1.dat", std::ios_base::binary | std::ios_base::out);

    char buf[3];
    buf[2] = 0;

    std::stringstream input(wut);
    input.flags(std::ios_base::hex);
    while (input)
    {
        input >> buf[0] >> buf[1];
        long val = strtol(buf, nullptr, 16);
        datafile << static_cast<unsigned char>(val & 0xff);
    }

}
+2

Peter R , 100% - , "0 ".

: "00000000", stringstream "000000".

, , :

// input: std::string hex; (e.g. = "180f00005e2c3415" or longer)
std::basic_string<uint8_t> bytes;

for (size_t i = 0; i < hex.length(); i += 2) {
    uint16_t byte;
    std::string nextbyte = hex.substr(i, 2);
    std::istringstream(nextbyte) >> std::hex >> byte;
    bytes.push_back(static_cast<uint8_t>(byte));
}

std::string result(begin(bytes), end(bytes));

Then you can simply write this line to a file as follows:

std::ofstream output_file("filename", std::ios::binary | std::ios::out);
if (output_file.is_open()) {
    output_file << result;
    output_file.close();
} else {
    std::cout << "Error could not create file." << std::endl;
}
0
source

All Articles