Skip to content

Instantly share code, notes, and snippets.

@yorickdewid
Created September 12, 2015 21:48
Show Gist options
  • Select an option

  • Save yorickdewid/0aa288f5f08d22cdbef5 to your computer and use it in GitHub Desktop.

Select an option

Save yorickdewid/0aa288f5f08d22cdbef5 to your computer and use it in GitHub Desktop.
Convert hex string to binary, alternative to sscanf()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_hex(unsigned char *s, size_t n) {
int i;
for (i=0; i<n; ++i)
printf("%02x", (unsigned int)s[i]);
printf("\n");
}
void hextobin(unsigned char *v, unsigned char *s, size_t n) {
int i;
char _t[3];
unsigned char *p = s;
for (i=0; i<n; ++i) {
memcpy(_t, p, 2);
_t[2] = '\0';
v[i] = (int)strtol(_t, NULL, 16);
p += 2;
}
}
int main(int argc, char *argv[]) {
char t[] = "de2779a7e8209172f5fe04912bfd1330c5ffac3da94f095fcdbcd331758a836b";
int n = strlen(t);
char v[n/2];
hextobin(v, t, n/2);
print_hex(v, n/2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment