diff --git a/util/hex.c b/util/hex.c new file mode 100644 index 0000000..2718fd1 --- /dev/null +++ b/util/hex.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include + +static int hex_encode(char **out, const void *ptr, size_t nbytes, + const char *digits) { + const uint8_t *bytes; + char *chars; + size_t i; + + assert(out != NULL); + assert(ptr != NULL); + assert(digits != NULL); + + *out = NULL; + bytes = ptr; + + chars = malloc(2 * nbytes + 1); + + if (chars == NULL) { + return -ENOMEM; + } + + for (i = 0; i < nbytes; i++) { + chars[i * 2 + 0] = digits[bytes[i] >> 4]; + chars[i * 2 + 1] = digits[bytes[i] & 15]; + } + + chars[nbytes * 2] = '\0'; + *out = chars; + + return 0; +} + +int hex_encode_lc(char **out, const void *bytes, size_t nbytes) { + assert(out != NULL); + assert(bytes != NULL); + + return hex_encode(out, bytes, nbytes, "0123456789abcdef"); +} + +int hex_encode_uc(char **out, const void *bytes, size_t nbytes) { + assert(out != NULL); + assert(bytes != NULL); + + return hex_encode(out, bytes, nbytes, "0123456789ABCDEF"); +} diff --git a/util/hex.h b/util/hex.h new file mode 100644 index 0000000..42ae643 --- /dev/null +++ b/util/hex.h @@ -0,0 +1,6 @@ +#pragma once + +#include + +int hex_encode_lc(char **out, const void *bytes, size_t nbytes); +int hex_encode_uc(char **out, const void *bytes, size_t nbytes); diff --git a/util/meson.build b/util/meson.build index d5cfcd7..a2a20c6 100644 --- a/util/meson.build +++ b/util/meson.build @@ -8,6 +8,8 @@ util_lib = static_library( 'crypto.h', 'fs.c', 'fs.h', + 'hex.c', + 'hex.h', 'iobuf.c', 'iobuf.h', 'list.c',