Cast string to hex

I have a string that comes from another program and looks like 414243 etc. and I want cast the values to hex (not convert) them for use in a char/unsigned char vector or array. E.g. char array[] = "\x41\x42\x43". Looking for guidance on how this can be done. I mainly have found answers on converting to hex, but that is not quite what I need to do. Any help would be appreciated.
What exactly do you mean by "convert", and why is it not a solution?

Show us an example of an answer you found, and why it doesn't work for you.
Last edited on
Perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <iostream>
#include <cctype>
using namespace std::string_literals;

std::string conv(const std::string& num)
{
	if (num.size() % 2)
		return {};

	std::string ashex;

	for (size_t s = 0; s < num.size(); ashex += ("\\x"s + num[s]) + num[s + 1], s += 2)
		if (!std::isxdigit(num[s]) || !std::isxdigit(num[s + 1]))
			return {};

	return ashex;
}

int main()
{
	const std::string num {"414243"};

	std::cout << conv(num) << '\n';
}



\x41\x42\x43

Last edited on
Thanks seeplus, that was exactly what I was looking to do.
Topic archived. No new replies allowed.