derbobo33 derbobo33 - 1 month ago 16x
C++ Question

Convert Hex String to unsigned Char

I have something like:

string hex = "\x80\x01";

and want to convert it to a unsigned char like:

unsigned char hex_char[] = "\x80\x01";

I tried
but it won't work since it doesn't support unsigned char

I would appreciate any suggestions.


For the in-practice you can just copy the values, any way you find natural.


using Byte = unsigned char;
string hex  = "\x80\x01";
vector<Byte> bytes( hex.begin(), hex.end() );

Or if you know that it will always be just two bytes,

using Byte = unsigned char;
string hex  = "\x80\x01";
Byte bytes[] = {{ hex[0], hex[1] }};

Formally it's a different kettle of fish, because with 8-bit byte the value \x80 won't fit as a positive signed char value. So it ends up as an implementation defined value. But in practice this is not a problem because computer evolution has converged on two's complement representation of signed integers, and I don't think there's any C++ compiler that doesn't use it.