Created
June 27, 2019 15:44
-
-
Save vpetrigo/dff05f18bdd1463e5fbdf0d319f64a72 to your computer and use it in GitHub Desktop.
Convert HEX string without spaces into an array of bytes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <ctype.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int main(void) | |
{ | |
char s[] = "CAFEDEADBEEF010203040506"; | |
size_t len = strlen(s); | |
unsigned char bytes[len / 2]; | |
for (size_t i = 0; i < len; i += 2) | |
{ | |
if (!isxdigit(s[i]) || !isxdigit(s[i + 1])) | |
{ | |
puts("Convert error"); | |
break; | |
} | |
sscanf(s + i, "%2hhx", &bytes[i / 2]); | |
} | |
for (size_t i = 0; i < sizeof bytes; ++i) | |
{ | |
printf("%02X", bytes[i]); | |
} | |
puts(""); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment