Reputation: 31
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.
Upvotes: 1
Views: 317
Reputation: 409136
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"
}
Upvotes: 4