From: Gerhard Sittig Date: Sat, 6 Oct 2018 17:02:03 +0000 (+0200) Subject: strutil: introduce hex dump routines (allocate a text buffer) X-Git-Url: https://sigrok.org/gitaction?a=commitdiff_plain;h=d8bc7ca3e6853bd4df33d9ff9405652abec8b67e;p=libsigrok.git strutil: introduce hex dump routines (allocate a text buffer) Introduce common support for hex dumps in the string util collection. There are explicit allocation and release routines for the textual representation of the data bytes, so that callers are free to chose whether and how to decorate the dump and where to send the message. --- diff --git a/src/libsigrok-internal.h b/src/libsigrok-internal.h index 317cad4a..a567d14b 100644 --- a/src/libsigrok-internal.h +++ b/src/libsigrok-internal.h @@ -1026,6 +1026,9 @@ SR_PRIV int sr_atof(const char *str, float *ret); SR_PRIV int sr_atod_ascii(const char *str, double *ret); SR_PRIV int sr_atof_ascii(const char *str, float *ret); +SR_PRIV GString *sr_hexdump_new(const uint8_t *data, const size_t len); +SR_PRIV void sr_hexdump_free(GString *s); + /*--- soft-trigger.c --------------------------------------------------------*/ struct soft_trigger_logic { diff --git a/src/strutil.c b/src/strutil.c index 73c9fc6a..93e424ee 100644 --- a/src/strutil.c +++ b/src/strutil.c @@ -590,6 +590,42 @@ SR_API int sr_vsnprintf_ascii(char *buf, size_t buf_size, #endif } +/** + * Convert a sequence of bytes to its textual representation ("hex dump"). + * + * Callers should free the allocated GString. See @ref sr_hexdump_free(). + * + * @param[in] data Pointer to the byte sequence to print. + * @param[in] len Number of bytes to print. + * + * @return #NULL upon error, newly allocated GString pointer otherwise. + */ +SR_PRIV GString *sr_hexdump_new(const uint8_t *data, const size_t len) +{ + GString *s; + size_t i; + + s = g_string_sized_new(3 * len); + for (i = 0; i < len; i++) { + if (i) + g_string_append_c(s, ' '); + g_string_append_printf(s, "%02x", data[i]); + } + + return s; +} + +/** + * Free a hex dump text that was created by @ref sr_hexdump_new(). + * + * @param[in] s Pointer to the GString to release. + */ +SR_PRIV void sr_hexdump_free(GString *s) +{ + if (s) + g_string_free(s, TRUE); +} + /** * Convert a string representation of a numeric value to a sr_rational. *