bananatools/util/hexstr.c

36 lines
1.0 KiB
C

#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);
}