1

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.

1
  • Please note that when you say "bytes xF1xF2xF3xF4 (4 bytes)" we might guess what you are trying to say, but this is not any widespread, or even slightly-spread notation. An accepted notation, since you want an array, would be [ 0xf1, 0xf2, 0xf3, 0xf4 ]. Commented Dec 12, 2019 at 14:51

1 Answer 1

4

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" } 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much. Now my EBCDIC to ASCII function requires a char pointer. How do I convert the vector to a C string or I guess I could adapt the function to accept a vector...
(char *)bytes.data() I guess
@RonC No, the vector is not null terminated. You could probably replace the std::vector<uint8_t> bytes with a std::string and do bytes += (char) std::stoi(byte_string, nullptr, 16); instead if you need a data() that is null terminated.
Now I'm struggling on the reverse--convert a std::string to a hex representation... i.e., [ 0xf1, 0xf2, 0xf3, 0xf4 ] to "F1F2F3F4"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.