From accdbc780617a4f4b30790ffb25ab1d26652c315 Mon Sep 17 00:00:00 2001 From: ben Date: Mon, 27 May 2019 21:40:41 +0200 Subject: First public release --- src/binhex.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/binhex.c (limited to 'src/binhex.c') diff --git a/src/binhex.c b/src/binhex.c new file mode 100644 index 0000000..f07aa45 --- /dev/null +++ b/src/binhex.c @@ -0,0 +1,67 @@ +// From https://nachtimwald.com/2017/09/24/hex-encode-and-decode-in-c/ + +#include +#include +#include "binhex.h" + +char *bin2hex(const unsigned char *bin, size_t len) +{ + char *out; + size_t i; + + if (bin == NULL || len == 0) + return NULL; + + out = malloc(len*2+1); + for (i=0; i> 4]; + out[i*2+1] = "0123456789ABCDEF"[bin[i] & 0x0F]; + } + out[len*2] = '\0'; + + return out; +} + +int hexchr2bin(const char hex, char *out) +{ + if (out == NULL) + return 0; + + if (hex >= '0' && hex <= '9') { + *out = hex - '0'; + } else if (hex >= 'A' && hex <= 'F') { + *out = hex - 'A' + 10; + } else if (hex >= 'a' && hex <= 'f') { + *out = hex - 'a' + 10; + } else { + return 0; + } + + return 1; +} + +size_t hexs2bin(const char *hex, unsigned char **out) +{ + size_t len; + char b1; + char b2; + size_t i; + + if (hex == NULL || *hex == '\0' || out == NULL) + return 0; + + len = strlen(hex); + if (len % 2 != 0) + return 0; + len /= 2; + + *out = malloc(len); + memset(*out, 'A', len); + for (i=0; i