From: Vadim Kochan <vadi...@gmail.com>

Add str2bytes func for converting hexadecimal string to bytes:

        "abcd a AA:BB" -> { 0xab 0xcd 0x0a 0xaa 0xbb }

It is needed to be used when specifying protocol payload for
trafgen proto command line.

Signed-off-by: Vadim Kochan <vadi...@gmail.com>
---
 str.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 str.h |  1 +
 2 files changed, 65 insertions(+)

diff --git a/str.c b/str.c
index ec221af..3fac290 100644
--- a/str.c
+++ b/str.c
@@ -5,6 +5,7 @@
  */
 
 #include <stdio.h>
+#include <ctype.h>
 #include <string.h>
 #include <stdarg.h>
 
@@ -109,3 +110,66 @@ char *cmdline_args2str(int from_idx, int argc, char **argv)
 
        return str;
 }
+
+static int strhex_bytes_len(char *str)
+{
+       int count = 0;
+
+       for (; *str; str++) {
+               if (!isxdigit(*str))
+                       continue;
+
+               if (isxdigit(*(str + 1)))
+                       str++;
+
+               count++;
+       }
+
+       return count;
+}
+
+static uint8_t char2hex(char c)
+{
+       int i;
+       const char *hex = "0123456789abcdef";
+       const char *hex_upper = "0123456789ABCDEF";
+
+       if (c >= 'A' && c <= 'F')
+               hex = hex_upper;
+
+       for (i = 0; i < 16; i++)
+               if (c == hex[i])
+                       return i;
+
+       return 0;
+}
+
+int str2bytes(char *str, uint8_t **bytes)
+{
+       int i;
+       int bytes_len;
+       uint8_t *byte;
+
+       if (!str || !*str)
+               return 0;
+
+       bytes_len = strhex_bytes_len(str);
+       byte = *bytes = xzmalloc(bytes_len);
+
+       for (; *str; str++) {
+               if (!isxdigit(*str))
+                       continue;
+
+               if (isxdigit(*(str + 1))) {
+                       *byte = (char2hex(*str) << 4) | char2hex(*(str + 1));
+                       str++;
+               } else {
+                       *byte = char2hex(*str);
+               }
+
+               byte++;
+               i++;
+       }
+
+       return bytes_len;
+}
diff --git a/str.h b/str.h
index 56456a0..9db4850 100644
--- a/str.h
+++ b/str.h
@@ -9,5 +9,6 @@ extern int slprintf_nocheck(char *dst, size_t size, const char 
*fmt, ...);
 extern char *strtrim_right(char *p, char c);
 extern noinline void *xmemset(void *s, int c, size_t n);
 extern char *cmdline_args2str(int from_idx, int argc, char **argv);
+extern int str2bytes(char *str, uint8_t **bytes);
 
 #endif /* STR_H */
-- 
2.4.2

-- 
You received this message because you are subscribed to the Google Groups 
"netsniff-ng" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to netsniff-ng+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to