util: add hexstring converter

This commit is contained in:
Hay1tsme 2023-04-13 02:30:39 -04:00
parent 8b57306c43
commit 4cf645cfc4
3 changed files with 44 additions and 0 deletions

36
util/hexstr.c Normal file
View File

@ -0,0 +1,36 @@
#include <windows.h>
#include <stdint.h>
#include <string.h>
#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);
}

6
util/hexstr.h Normal file
View File

@ -0,0 +1,6 @@
#pragma once
#include <windows.h>
#include <stdint.h>
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);

View File

@ -21,5 +21,7 @@ util_lib = static_library(
'lib.h',
'str.c',
'str.h',
'hexstr.c',
'hexstr.h',
],
)