Reputation: 390
I am working in C++ and let's say I have the following hexadecimal as a string
string key = "F3D5";
how can I convert it to an array of uint8_t
?
Actually, I have an algorithm that generate a key of type uint8_t*
, and I convert this key to hexadecimal using the following code :
uint8_t key = generateKey();
vector<uint8_t> keyVector(begin(key), end(key));
string hexadecimalKey= uint8_vector_to_hex_string(keyVector);
This is the method that convert uint8 vector to hexadecimal in string :
string uint8_vector_to_hex_string(const vector<uint8_t>& v) {
stringstream ss;
ss << hex << setfill('0');
vector<uint8_t>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
ss << setw(2) << static_cast<unsigned>(*it);
}
return ss.str();
}
And I would like to re-convert the hexadecimalKey
to uint8_t, with the following code
uint8_t* convertedKey = hex_string_to_uint8_t(hexadecimalKey);
with the following method :
uint8_t* hex_string_to_uint8_t(string value) {
size_t len = value.length();
vector<uint8_t> out;
for (size_t i = 0; i < len; i += 2) {
std::istringstream strm(value.substr(i, 2));
uint8_t x;
strm >> std::hex >> x;
out.push_back(x);
}
return out.data();
}
and whenever i do that, the convertedKey
is not equal to key
I need your help.
Thank you, really appreciate it
Upvotes: 3
Views: 6411
Reputation: 414
You can use the function below:
uint8_t* hex_str_to_uint8(const char* string) {
if (string == NULL)
return NULL;
size_t slength = strlen(string);
if ((slength % 2) != 0) // must be even
return NULL;
size_t dlength = slength / 2;
uint8_t* data = (uint8_t*)malloc(dlength);
memset(data, 0, dlength);
size_t index = 0;
while (index < slength) {
char c = string[index];
int value = 0;
if (c >= '0' && c <= '9')
value = (c - '0');
else if (c >= 'A' && c <= 'F')
value = (10 + (c - 'A'));
else if (c >= 'a' && c <= 'f')
value = (10 + (c - 'a'));
else
return NULL;
data[(index / 2)] += value << (((index + 1) % 2) * 4);
index++;
}
return data;
}
Good luck!
Upvotes: 4
Reputation: 1
Looks like it works, but you should work on lining everything up -- make everything in the same block (section of code with {}) line up, and then intent after a { and put each } on a new line. Or follow some other coding standard, I don't care. Just make it line up and indent.
Also, you could make it ever so slightly more efficient by making tmp just a char (not an array) and then using it to store the third character, setting that character to NULL, and then restoring it after strtol.
char buf[] = "4142434445";
uint8_t tx_buffer[20];
uint8_t len_buffer=0;
for(i=0;i<strlen(buf);i+=2) {
char tmp = buf[i+3];
buf[i+3] = 0;
tx_buffer[len_buffer] = strtol(buf,NULL,16);
len_buffer++;
buf[i+3] = tmp;
}
Upvotes: -1