From c07f5397f48b75f030acf904e6572b6ee083953f Mon Sep 17 00:00:00 2001 From: Victor Julien Date: Fri, 31 Jan 2014 12:21:47 +0100 Subject: [PATCH] Introduce BytesToString utility Introduce a utility function to convert an array of bytes into a null-terminated string: char *BytesToString(const uint8_t *bytes, size_t nbytes); All non-printables are copied over, except for '\0', which is turned into literal '\' '0' in the string. So the resulting string may be bigger than the input. --- src/util-byte.c | 43 +++++++++++++++++++++++++++++++++++++++++++ src/util-byte.h | 11 +++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/util-byte.c b/src/util-byte.c index e3d276b2a2..65bf35baa1 100644 --- a/src/util-byte.c +++ b/src/util-byte.c @@ -28,6 +28,49 @@ #include "util-unittest.h" #include "util-debug.h" +/** \brief Turn byte array into string. + * + * All non-printables are copied over, except for '\0', which is + * turned into literal \0 in the string. + * + * \param bytes byte array + * \param nbytes number of bytes + * \return string nul-terminated string or NULL on error + */ +char *BytesToString(const uint8_t *bytes, size_t nbytes) +{ + size_t n = nbytes + 1; + size_t nulls = 0; + + size_t u; + for (u = 0; u < nbytes; u++) { + if (bytes[u] == '\0') + nulls++; + } + n += nulls; + + char *string = SCCalloc(1, n); + if (string == NULL) + return NULL; + + if (nulls == 0) { + /* no nulls */ + memcpy(string, bytes, nbytes); + } else { + /* no nulls present */ + char *dst = string; + for (u = 0; u < n; u++) { + if (bytes[u] == '\0') { + *dst++ = '\\'; + *dst++ = '0'; + } else { + *dst++ = bytes[u]; + } + } + } + return string; +} + int ByteExtractUint64(uint64_t *res, int e, uint16_t len, const uint8_t *bytes) { uint64_t i64; diff --git a/src/util-byte.h b/src/util-byte.h index 8175e5ca63..82c16a4d1c 100644 --- a/src/util-byte.h +++ b/src/util-byte.h @@ -71,6 +71,17 @@ #define SCByteSwap64(x) bswap_64(x) #endif /* OS_FREEBSD */ +/** \brief Turn byte array into string. + * + * All non-printables are copied over, except for '\0', which is + * turned into literal \0 in the string. + * + * \param bytes byte array + * \param nbytes number of bytes + * \return string nul-terminated string or NULL on error + */ +char *BytesToString(const uint8_t *bytes, size_t nbytes); + /** * Extract bytes from a byte string and convert to a unint64_t. *