0

I am using this code from Integer to hex string in C++ to convert std::vector to string to insert on a database. It is working, but now i need to reverse, to take the hex std::string and convert it back to std::vector

I have no idea on the proper way to do this. Should i just take every 2 chars and convert it to decimal and add to std::vector ?

std::string hexify(std::vector<unsigned char> const& v)
{
    std::stringstream ss;
    for (auto c : v)
    {
        //ss << std::hex << (int)c;
        ss << std::setw(2) << std::setfill('0') << std::hex << (int)c;
    }
    return ss.str();
}
uacaman
  • 418
  • 1
  • 5
  • 15
  • It feels a bit weird. Why do you need to cast the characters into decimals in the first place? Thought a hex string still uses 1 character each digits, just using A~F. – Uduru May 07 '22 at 03:39

2 Answers2

1

This works for you

std::vector<unsigned char> unhexify(std::string const &s) {
  std::vector<unsigned char> v;
  for (size_t i = 0; i < s.size(); i += 2) {
    auto substr = s.substr(i, 2);
    auto chr_int = std::stoi(substr, nullptr, 16);
    v.push_back(chr_int);
  }
  return v;
}

enter image description here

Testing

#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

std::string hexify(std::vector<unsigned char> const &v) {
  std::stringstream ss;
  for (auto c : v) {
    // ss << std::hex << (int)c;
    ss << std::setw(2) << std::setfill('0') << std::hex << (int)c;
  }
  return ss.str();
}

std::vector<unsigned char> unhexify(std::string const &s) {
  std::vector<unsigned char> v;
  for (size_t i = 0; i < s.size(); i += 2) {
    auto substr = s.substr(i, 2);
    auto chr_int = std::stoi(substr, nullptr, 16);
    v.push_back(chr_int);
  }
  return v;
}

void print_vector(std::vector<unsigned char> const &v) {
  // two bytes a group
  for (size_t i = 0; i < v.size(); i += 1) {
    std::cout << v[i] << " ";
  }
  std::cout << std::endl;
}

int main() {
  std::vector<unsigned char> v = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
//   std::vector<unsigned char> v = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
  std::string s = hexify(v);
  std::cout << s << std::endl;
  print_vector(unhexify(s));
}
Pluveto
  • 456
  • 5
  • 9
0

This seems like the conversion you seek.

For each two letters in the string named s, pass as standalone string to the library function: strtoul to convert back to an unsigned value.

#include <stdlib.h>

void unhexify(const std::string& s, std::vector<unsigned char>& v)
{
   size_t len = s.size() / 2;
   v.clear();

   for (size_t i = 0; i < len; len++)
   {
       char sz[3] = {s[i*2], s[i*2+1], '\0'};
       unsigned char uc = (unsigned char)(strtoul(sz, NULL, 16));
       v.push_back(uc);
   }
}
selbie
  • 100,020
  • 15
  • 103
  • 173