11#ifndef IMPULSE_HEXIO_H
12#define IMPULSE_HEXIO_H
24 if (c >=
'0' && c <=
'9')
return c -
'0';
25 if (c >=
'a' && c <=
'f')
return c -
'a' + 10;
26 if (c >=
'A' && c <=
'F')
return c -
'A' + 10;
36 size_t offset,
size_t count,
37 char* out_hex,
size_t out_hex_cap) {
38 static const char kHexDigits[] =
"0123456789ABCDEF";
39 if (!buf || !out_hex || offset > buf_len || count > buf_len - offset ||
40 count > (SIZE_MAX - 1) / 2 || out_hex_cap < count * 2 + 1) {
43 for (
size_t i = 0; i < count; ++i) {
44 uint8_t b = buf[offset + i];
45 out_hex[i * 2] = kHexDigits[(b >> 4) & 0x0F];
46 out_hex[i * 2 + 1] = kHexDigits[b & 0x0F];
48 out_hex[count * 2] =
'\0';
58 size_t offset,
const char* hex_str) {
59 if (!buf || !hex_str || offset > buf_len)
return -1;
61 const char* p = hex_str;
63 while (*p ==
' ' || *p ==
'\t' || *p ==
'\r' || *p ==
'\n') ++p;
64 if (*p ==
'\0')
break;
67 if (hi < 0 || lo < 0)
return -1;
68 if (offset + written >= buf_len)
return -1;
69 buf[offset + written] = (uint8_t)((hi << 4) | lo);
80 char* out_hex,
size_t out_hex_cap) {
81 if (!path || !out_hex || out_hex_cap < count * 2 + 1)
return -1;
82 FILE* f = fopen(path,
"rb");
84 if (fseek(f, (
long)offset, SEEK_SET) != 0) {
88 static const char kHexDigits[] =
"0123456789ABCDEF";
89 for (
size_t i = 0; i < count; ++i) {
95 uint8_t b = (uint8_t)c;
96 out_hex[i * 2] = kHexDigits[(b >> 4) & 0x0F];
97 out_hex[i * 2 + 1] = kHexDigits[b & 0x0F];
99 out_hex[count * 2] =
'\0';
108 if (!path || !hex_str)
return -1;
109 FILE* f = fopen(path,
"r+b");
111 if (fseek(f, (
long)offset, SEEK_SET) != 0) {
116 const char* p = hex_str;
118 while (*p ==
' ' || *p ==
'\t' || *p ==
'\r' || *p ==
'\n') ++p;
119 if (*p ==
'\0')
break;
122 if (hi < 0 || lo < 0) {
126 uint8_t b = (uint8_t)((hi << 4) | lo);
127 if (fputc(b, f) == EOF) {
142 bytes[0] = (uint8_t)(val & 0xFFu);
143 bytes[1] = (uint8_t)((val >> 8) & 0xFFu);
150 for (
int i = 0; i < 4; ++i) bytes[i] = (uint8_t)((val >> (i * 8)) & 0xFFu);
157 for (
int i = 0; i < 8; ++i) bytes[i] = (uint8_t)((val >> (i * 8)) & 0xFFu);
static int impulse_hexio_nibble(char c)
Definition impulse_hexio.h:23
static int impulse_hexio_read_buf(const uint8_t *buf, size_t buf_len, size_t offset, size_t count, char *out_hex, size_t out_hex_cap)
Definition impulse_hexio.h:35
static void impulse_hexio_render_u32_le(uint32_t val, char out_hex[9])
Definition impulse_hexio.h:148
static void impulse_hexio_render_u16_le(uint16_t val, char out_hex[5])
Definition impulse_hexio.h:140
static int impulse_hexio_write_file(const char *path, size_t offset, const char *hex_str)
Definition impulse_hexio.h:107
static void impulse_hexio_render_u64_le(uint64_t val, char out_hex[17])
Definition impulse_hexio.h:155
static int impulse_hexio_write_buf(uint8_t *buf, size_t buf_len, size_t offset, const char *hex_str)
Definition impulse_hexio.h:57
static int impulse_hexio_read_file(const char *path, size_t offset, size_t count, char *out_hex, size_t out_hex_cap)
Definition impulse_hexio.h:79