]> mj.ucw.cz Git - libucw.git/blob - ucw/str-hex.c
Conf: Introduced cf_set_journalling()
[libucw.git] / ucw / str-hex.c
1 /*
2  *      UCW Library -- Hexdumping and Unhexdumping
3  *
4  *      (c) 2008 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/string.h>
12 #include <ucw/chartype.h>
13
14 static uns
15 hex_make(uns x)
16 {
17   return (x < 10) ? (x + '0') : (x - 10 + 'a');
18 }
19
20 void
21 mem_to_hex(char *dest, const byte *src, uns bytes, uns flags)
22 {
23   uns sep = flags & 0xff;
24
25   while (bytes--)
26     {
27       dest[0] = hex_make(*src >> 4);
28       dest[1] = hex_make(*src & 0x0f);
29       if (flags & MEM_TO_HEX_UPCASE)
30         {
31           dest[0] = Cupcase(dest[0]);
32           dest[1] = Cupcase(dest[1]);
33         }
34       dest += 2;
35       if (sep && bytes)
36         *dest++ = sep;
37       src++;
38     }
39   *dest = 0;
40 }
41
42 static uns
43 hex_parse(uns c)
44 {
45   c = Cupcase(c);
46   c -= '0';
47   return (c < 10) ? c : (c - 7);
48 }
49
50 const char *
51 hex_to_mem(byte *dest, const char *src, uns max_bytes, uns flags)
52 {
53   uns sep = flags & 0xff;
54   while (max_bytes-- && Cxdigit(src[0]) && Cxdigit(src[1]))
55     {
56       *dest++ = (hex_parse(src[0]) << 4) | hex_parse(src[1]);
57       src += 2;
58       if (sep && *src && max_bytes)
59         {
60           if (*src != (char)sep)
61             return src;
62           src++;
63         }
64     }
65   return src;
66 }
67
68 #ifdef TEST
69
70 #include <stdio.h>
71
72 int main(void)
73 {
74   byte x[4] = { 0xfe, 0xed, 0xf0, 0x0d };
75   byte y[4];
76   char a[16];
77
78   mem_to_hex(a, x, 4, MEM_TO_HEX_UPCASE);
79   puts(a);
80   mem_to_hex(a, x, 4, ':');
81   puts(a);
82   const char *z = hex_to_mem(y, a, 4, ':');
83   if (*z)
84     puts("BAD");
85   else
86     printf("%02x%02x%02x%02x\n", y[0], y[1], y[2], y[3]);
87
88   return 0;
89 }
90
91 #endif