libacfutils
A general purpose library of utility functions designed to make it easier to develop addons for the X-Plane flight simulator.
Loading...
Searching...
No Matches
hexcode.c
1/*
2 * CDDL HEADER START
3 *
4 * This file and its contents are supplied under the terms of the
5 * Common Development and Distribution License ("CDDL"), version 1.0.
6 * You may only use this file in accordance with the terms of version
7 * 1.0 of the CDDL.
8 *
9 * A full copy of the text of the CDDL should have accompanied this
10 * source. A copy of the CDDL is also available via the Internet at
11 * http://www.illumos.org/license/CDDL.
12 *
13 * CDDL HEADER END
14*/
15/*
16 * Copyright 2023 Saso Kiselkov. All rights reserved.
17 */
18
19#include <ctype.h>
20#include <stdint.h>
21#include <stdio.h>
22
23#include "acfutils/assert.h"
24#include "acfutils/hexcode.h"
25
37API_EXPORT void
38hex_enc(const void *in_raw, size_t len, void *out_enc, size_t out_cap)
39{
40 const uint8_t *in_8b = in_raw;
41 char *out = out_enc;
42
43 ASSERT(in_raw != NULL || len == 0);
44 ASSERT(out_enc != NULL || out_cap == 0);
45
46 /* guarantee zero-termination of output */
47 if (out_cap != 0)
48 *out = 0;
49 for (size_t i = 0, j = 0; i < len && j + 3 <= out_cap; i++, j += 2)
50 sprintf(&out[j], "%02x", (unsigned)in_8b[i]);
51}
52
53static inline int
54xdigit2int(char c)
55{
56 if (c >= '0' && c <= '9')
57 return (c - '0');
58 if (c >= 'A' && c <= 'F')
59 return (c - 'A' + 10);
60 if (c >= 'a' && c <= 'f')
61 return (c - 'a' + 10);
62 return (-1);
63}
64
83API_EXPORT bool_t
84hex_dec(const void *in_enc, size_t len, void *out_raw, size_t out_cap)
85{
86 const char *in_str = in_enc;
87 uint8_t *out = out_raw;
88
89 /* Input length must be a multiple of two and fit into output */
90 if ((len % 2 != 0) || (out_cap < len / 2))
91 return (B_FALSE);
92
93 for (size_t i = 0, j = 0; i < len && j < out_cap; i += 2, j++) {
94 int a = xdigit2int(in_str[i]);
95 int b = xdigit2int(in_str[i + 1]);
96
97 if (a == -1 || b == -1)
98 return (B_FALSE);
99 out[j] = (a << 4) | b;
100 }
101
102 return (B_TRUE);
103}
#define ASSERT(x)
Definition assert.h:208
bool_t hex_dec(const void *in_enc, size_t len, void *out_raw, size_t out_cap)
Definition hexcode.c:84
void hex_enc(const void *in_raw, size_t len, void *out_enc, size_t out_cap)
Definition hexcode.c:38