Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding a hex encoded string using a stringstream

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.

like image 256
goji Avatar asked Apr 25 '26 15:04

goji


2 Answers

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.

like image 166
Some programmer dude Avatar answered Apr 28 '26 06:04

Some programmer dude


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.

like image 20
Jerry Coffin Avatar answered Apr 28 '26 05:04

Jerry Coffin