Skip to content

Instantly share code, notes, and snippets.

@vpetrigo
Created June 27, 2019 15:44
Show Gist options
  • Save vpetrigo/dff05f18bdd1463e5fbdf0d319f64a72 to your computer and use it in GitHub Desktop.
Save vpetrigo/dff05f18bdd1463e5fbdf0d319f64a72 to your computer and use it in GitHub Desktop.
Convert HEX string without spaces into an array of bytes
#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