I've searched Stackoverflow, and there are many answers - but not to the exact problem that I'm seeing (using gcc on macOS, if that makes a difference - Mac specific suggestions won't do though because I need this to be cross platform). I know how to convert a string to Hex into a buffer - or, at least, I thought I did. I do it like this:
unsigned char* buffer_from_hexstring(char* string) {
unsigned char* HexBuffer = (unsigned char *)malloc( (strlen(string) / 2) * sizeof(unsigned char) );
for (size_t count = 0; count < strlen(string); count++) {
sscanf(string, "%2hhx", &HexBuffer[count]);
string += 2;
}
return HexBuffer;
}
I call my function as follows:
int main(int argc, char *argv[]) {
char* hexstring = "beefcafebeefcafebeefcafe";
unsigned char* buffer = buffer_from_hexstring(hexstring);
printf("Result: ");
for(size_t count = 0; count < (sizeof(buffer) * sizeof(*buffer)); count++) {
printf("%02x", buffer[count]);
}
free(buffer);
}
And the result that I get is beefcafebeefcafe
. I'm missing a beefcafe. In fact, whatever I do I only get 16bytes back - which is no useful if I want to convert more bytes.
I'm sure that it's an obvious error - but I can't see it. Can you?