简体   繁体   中英

C++ Convert Hex String Representation to Hex

I have searched here for an answer and either didn't find it or didn't understand it.

I need to convert a std::string such as "F1F2F3F4" (8 bytes) to bytes \\xF1\\xF2\\xF3\\xF4 (4 bytes).

I think I need std::hex but I'm confused by the examples I saw. After the conversion I need to access those bytes (as a char array) so that I can convert them to ASCII from EBCDIC (but that's another story).

So I think it would be something like this:

somevariable << std::hex << InputString;

But what should I use as somevariable? By the way, the InputString can be any length from 1 to 50-something or so.

My compiler is g++ 4.8 on Linux.

A simple (and slightly naive) way is to get two characters at a time from the input string, put in another string that you then pass to std::stoi (or std::strtoul if you don't have std::stoi ) to convert to an integer that you can then put into a byte array.

For example something like this:

std::vector<uint8_t> bytes;  // The output "array" of bytes
std::string input = "f1f2f4f4";  // The input string

for (size_t i = 0; i < input.length(); i += 2)  // +2 because we get two characters at a time
{
    std::string byte_string(&input[i], 2);  // Construct temporary string for
                                            // the next two character from the input

    int byte_value = std::stoi(byte_string, nullptr, 16);  // Base 16
    bytes.push_back(byte_value);  // Add to the byte "array"
}

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