1 /* 2 * Copyright (c) 2022-2026 Bjoern A. Zeeb 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7 #ifndef _LINUXKPI_LINUX_HEX_H_ 8 #define _LINUXKPI_LINUX_HEX_H_ 9 10 #include <linux/types.h> 11 #include <linux/errno.h> 12 13 static inline int _h2b(const char c)14_h2b(const char c) 15 { 16 17 if (c >= '0' && c <= '9') 18 return (c - '0'); 19 if (c >= 'a' && c <= 'f') 20 return (10 + c - 'a'); 21 if (c >= 'A' && c <= 'F') 22 return (10 + c - 'A'); 23 return (-EINVAL); 24 } 25 26 static inline int hex2bin(uint8_t * bindst,const char * hexsrc,size_t binlen)27hex2bin(uint8_t *bindst, const char *hexsrc, size_t binlen) 28 { 29 int hi4, lo4; 30 31 while (binlen > 0) { 32 hi4 = _h2b(*hexsrc++); 33 lo4 = _h2b(*hexsrc++); 34 if (hi4 < 0 || lo4 < 0) 35 return (-EINVAL); 36 37 *bindst++ = (hi4 << 4) | lo4; 38 binlen--; 39 } 40 41 return (0); 42 } 43 44 #endif /* _LINUXKPI_LINUX_HEX_H_ */ 45