From 4cf645cfc4f58b7612bdbba73158daecb0c0aef4 Mon Sep 17 00:00:00 2001 From: Kevin Trocolli Date: Thu, 13 Apr 2023 02:30:39 -0400 Subject: [PATCH] util: add hexstring converter --- util/hexstr.c | 36 ++++++++++++++++++++++++++++++++++++ util/hexstr.h | 6 ++++++ util/meson.build | 2 ++ 3 files changed, 44 insertions(+) create mode 100644 util/hexstr.c create mode 100644 util/hexstr.h diff --git a/util/hexstr.c b/util/hexstr.c new file mode 100644 index 0000000..1c41588 --- /dev/null +++ b/util/hexstr.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include "util/hexstr.h" +#include "util/dprintf.h" + +HRESULT str_to_bytes(const char *str_in, const size_t str_len, uint8_t *bfr, const size_t bfr_size) +{ + if (str_len % 2 != 0) { return E_INVALIDARG; } + + for (int i = 0; i < str_len; i += 2) { + if (i >= bfr_size * 2) { break; } + + char high_c = str_in[i]; + char low_c = str_in[i + 1]; + uint8_t val_h = 0; + uint8_t val_l = 0; + uint8_t val = 0; + + // I hate c + val_l = (strtol(&low_c, 0, 16) & 0xF0) >> 4; + val_h = strtol(&high_c, 0, 16); + bfr[i / 2] = (val_h << 4) + val_l; + //dprintf("Util: %c %c -> 0x%X 0x%X -> 0x%02X\n", high_c, low_c, val_h, val_l, bfr[i / 2]); + } + + return S_OK; +} + +// TODO +HRESULT wstr_to_bytes(const wchar_t *str_in, const size_t str_len, uint8_t *bfr, const size_t bfr_size) +{ + char buffer[100]; + wcstombs(buffer, str_in, sizeof(buffer)); + return str_to_bytes(buffer, str_len, bfr, bfr_size); +} \ No newline at end of file diff --git a/util/hexstr.h b/util/hexstr.h new file mode 100644 index 0000000..f931e2b --- /dev/null +++ b/util/hexstr.h @@ -0,0 +1,6 @@ +#pragma once +#include +#include + +HRESULT str_to_bytes(const char *str_in, const size_t str_len, uint8_t *bfr, const size_t bfr_size); +HRESULT wstr_to_bytes(const wchar_t *str_in, const size_t str_len, uint8_t *bfr, const size_t bfr_size); \ No newline at end of file diff --git a/util/meson.build b/util/meson.build index 575d123..d7a646f 100644 --- a/util/meson.build +++ b/util/meson.build @@ -21,5 +21,7 @@ util_lib = static_library( 'lib.h', 'str.c', 'str.h', + 'hexstr.c', + 'hexstr.h', ], )