From 513146497f7ddcf560496bfdff06f7adc2e3eb84 Mon Sep 17 00:00:00 2001 From: Martin Mares Date: Wed, 25 Jun 2008 21:11:17 +0200 Subject: [PATCH] Added a simple module for making and parsing hexdumps. --- lib/Makefile | 2 +- lib/str-hex.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ lib/string.h | 5 ++++ 3 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 lib/str-hex.c diff --git a/lib/Makefile b/lib/Makefile index 3b3f259f..1196df8f 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -31,7 +31,7 @@ LIBUCW_MODS= \ base64 base224 \ sync \ qache \ - string str-esc str-split str-match str-imatch \ + string str-esc str-split str-match str-imatch str-hex \ bbuf \ getopt diff --git a/lib/str-hex.c b/lib/str-hex.c new file mode 100644 index 00000000..3dd3e438 --- /dev/null +++ b/lib/str-hex.c @@ -0,0 +1,71 @@ +/* + * UCW Library -- Hexdumping and Unhexdumping + * + * (c) 2008 Martin Mares + * + * This software may be freely distributed and used according to the terms + * of the GNU Lesser General Public License. + */ + +#include "lib/lib.h" +#include "lib/string.h" +#include "lib/chartype.h" + +static uns +hex_make(uns x) +{ + return (x < 10) ? (x + '0') : (x - 10 + 'a'); +} + +void +mem_to_hex(char *dest, const byte *src, uns bytes) +{ + while (bytes--) + { + *dest++ = hex_make(*src >> 4); + *dest++ = hex_make(*src & 0x0f); + src++; + } + *dest = 0; +} + +static uns +hex_parse(uns c) +{ + c = Cupcase(c); + c -= '0'; + return (c < 10) ? c : (c - 7); +} + +const char * +hex_to_mem(byte *dest, const char *src, uns max_bytes) +{ + while (max_bytes-- && Cxdigit(src[0]) && Cxdigit(src[1])) + { + *dest++ = (hex_parse(src[0]) << 4) | hex_parse(src[1]); + src += 2; + } + return src; +} + +#ifdef TEST + +#include + +int main(void) +{ + byte x[4] = { 0xfe, 0xed, 0xf0, 0x0d }; + byte y[4]; + char a[10]; + + mem_to_hex(a, x, 4); + puts(a); + const char *z = hex_to_mem(y, a, 4); + if (*z) + return 1; + printf("%02x%02x%02x%02x\n", y[0], y[1], y[2], y[3]); + + return 0; +} + +#endif diff --git a/lib/string.h b/lib/string.h index 50c4dc47..6b0ed593 100644 --- a/lib/string.h +++ b/lib/string.h @@ -29,6 +29,11 @@ int str_wordsplit(char *str, char **rec, uns max); int str_match_pattern(const char *patt, const char *str); int str_match_pattern_nocase(const char *patt, const char *str); +/* str-hex.c */ + +void mem_to_hex(char *dest, const byte *src, uns bytes); +const char *hex_to_mem(byte *dest, const char *src, uns max_bytes); + /* md5hex.c */ void md5_to_hex(const byte *s, char *d); -- 2.39.2