1 /*
2 * Copyright (c) 2019 Nordic Semiconductor ASA
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <stddef.h>
8 #include <zephyr/types.h>
9 #include <errno.h>
10 #include <zephyr/sys/util.h>
11
char2hex(char c,uint8_t * x)12 int char2hex(char c, uint8_t *x)
13 {
14 if ((c >= '0') && (c <= '9')) {
15 *x = c - '0';
16 } else if ((c >= 'a') && (c <= 'f')) {
17 *x = c - 'a' + 10;
18 } else if ((c >= 'A') && (c <= 'F')) {
19 *x = c - 'A' + 10;
20 } else {
21 return -EINVAL;
22 }
23
24 return 0;
25 }
26
hex2char(uint8_t x,char * c)27 int hex2char(uint8_t x, char *c)
28 {
29 if (x <= 9) {
30 *c = x + (char)'0';
31 } else if (x <= 15) {
32 *c = x - 10 + (char)'a';
33 } else {
34 return -EINVAL;
35 }
36
37 return 0;
38 }
39
bin2hex(const uint8_t * buf,size_t buflen,char * hex,size_t hexlen)40 size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen)
41 {
42 if (hexlen < ((buflen * 2U) + 1U)) {
43 return 0;
44 }
45
46 for (size_t i = 0; i < buflen; i++) {
47 hex2char(buf[i] >> 4, &hex[2U * i]);
48 hex2char(buf[i] & 0xf, &hex[2U * i + 1U]);
49 }
50
51 hex[2U * buflen] = '\0';
52 return 2U * buflen;
53 }
54
hex2bin(const char * hex,size_t hexlen,uint8_t * buf,size_t buflen)55 size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen)
56 {
57 uint8_t dec;
58
59 if (buflen < (hexlen / 2U + hexlen % 2U)) {
60 return 0;
61 }
62
63 /* if hexlen is uneven, insert leading zero nibble */
64 if ((hexlen % 2U) != 0) {
65 if (char2hex(hex[0], &dec) < 0) {
66 return 0;
67 }
68 buf[0] = dec;
69 hex++;
70 buf++;
71 }
72
73 /* regular hex conversion */
74 for (size_t i = 0; i < (hexlen / 2U); i++) {
75 if (char2hex(hex[2U * i], &dec) < 0) {
76 return 0;
77 }
78 buf[i] = dec << 4;
79
80 if (char2hex(hex[2U * i + 1U], &dec) < 0) {
81 return 0;
82 }
83 buf[i] += dec;
84 }
85
86 return hexlen / 2U + hexlen % 2U;
87 }
88