It's easy to hex encode a string using a stringstream, but is it possible to do the reverse and decode the resulting string with a stringstream?
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
int main()
{
std::string test = "hello, world";
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (unsigned ch : test)
ss << std::setw(2) << int(ch);
std::cout << ss.str() << std::endl;
}
I'm not looking to bit shift the bytes directly or use old c functions such as the scanf family of functions.
Not quite as easy, if you just have a stream of hexadecimal digits with no separator. You can use std::basic_istream::get or std::basic_istream::read to extract two digits at a time, and then use e.g. std::stoi to convert to an integer which can then be type-casted to a char.
It is if you put some sort of separator between the numbers. Just for example, let's start by changing your code to insert a space between each byte of output:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
int main()
{
std::string test = "hello, world";
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (unsigned ch : test)
ss << std::setw(2) << int(ch) << " ";
std::cout << ss.str() << std::endl;
}
Then, let's write a little program to read that data from cin, and print it out as characters again:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
int main()
{
int i;
while (std::cin >> std::hex >> i)
std::cout << static_cast<char>(i);
return 0;
}
When I run these with the first piped to the second, I get hello, world as the output.
Obviously enough, reading the data from a stringstream works about the same as reading from std::cin -- I used cin so I could demonstrate while leaving your code nearly intact.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With