xref: /openbmc/u-boot/include/hexdump.h (revision 3ba98ed8)
1 /* SPDX-License-Identifier: GPL-2.0+ */
2 /*
3  * Copyright (C) 2018 Synopsys, Inc. All rights reserved.
4  *
5  */
6 
7 #ifndef HEXDUMP_H
8 #define HEXDUMP_H
9 
10 #include <linux/ctype.h>
11 #include <linux/types.h>
12 
13 enum {
14 	DUMP_PREFIX_NONE,
15 	DUMP_PREFIX_ADDRESS,
16 	DUMP_PREFIX_OFFSET
17 };
18 
19 extern const char hex_asc[];
20 #define hex_asc_lo(x)	hex_asc[((x) & 0x0f)]
21 #define hex_asc_hi(x)	hex_asc[((x) & 0xf0) >> 4]
22 
23 static inline char *hex_byte_pack(char *buf, u8 byte)
24 {
25 	*buf++ = hex_asc_hi(byte);
26 	*buf++ = hex_asc_lo(byte);
27 	return buf;
28 }
29 
30 /**
31  * hex_to_bin - convert a hex digit to its real value
32  * @ch: ascii character represents hex digit
33  *
34  * hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
35  * input.
36  */
37 static inline int hex_to_bin(char ch)
38 {
39 	if ((ch >= '0') && (ch <= '9'))
40 		return ch - '0';
41 	ch = tolower(ch);
42 	if ((ch >= 'a') && (ch <= 'f'))
43 		return ch - 'a' + 10;
44 	return -1;
45 }
46 
47 /**
48  * hex2bin - convert an ascii hexadecimal string to its binary representation
49  * @dst: binary result
50  * @src: ascii hexadecimal string
51  * @count: result length
52  *
53  * Return 0 on success, -1 in case of bad input.
54  */
55 static inline int hex2bin(u8 *dst, const char *src, size_t count)
56 {
57 	while (count--) {
58 		int hi = hex_to_bin(*src++);
59 		int lo = hex_to_bin(*src++);
60 
61 		if ((hi < 0) || (lo < 0))
62 			return -1;
63 
64 		*dst++ = (hi << 4) | lo;
65 	}
66 	return 0;
67 }
68 
69 /**
70  * bin2hex - convert binary data to an ascii hexadecimal string
71  * @dst: ascii hexadecimal result
72  * @src: binary data
73  * @count: binary data length
74  */
75 static inline char *bin2hex(char *dst, const void *src, size_t count)
76 {
77 	const unsigned char *_src = src;
78 
79 	while (count--)
80 		dst = hex_byte_pack(dst, *_src++);
81 	return dst;
82 }
83 
84 int hex_dump_to_buffer(const void *buf, size_t len, int rowsize, int groupsize,
85 		       char *linebuf, size_t linebuflen, bool ascii);
86 void print_hex_dump(const char *prefix_str, int prefix_type, int rowsize,
87 		    int groupsize, const void *buf, size_t len, bool ascii);
88 void print_hex_dump_bytes(const char *prefix_str, int prefix_type,
89 			  const void *buf, size_t len);
90 
91 #endif /* HEXDUMP_H */
92