From 3f8ce32429184fb0d06e7b2534411126398477f7 Mon Sep 17 00:00:00 2001 From: Frederic Borry Date: Tue, 8 Oct 2024 19:40:12 +0200 Subject: [PATCH 1/2] Added utility method for SCPI protocol debugging. --- log.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ log.h | 2 ++ 2 files changed, 45 insertions(+) diff --git a/log.cpp b/log.cpp index c8293fd..1febb8c 100644 --- a/log.cpp +++ b/log.cpp @@ -432,3 +432,46 @@ void Log(Severity severity, const char *format, ...) va_end(va); } } + +/** + * @brief Convert a sequence of bytes to its textual representation ("hex dump"). + * + * @param data Pointer to the byte sequence to print. + * @param len Number of bytes to print. + * + * @return string representation of the data buffer. + * + */ +string LogHexDump(const unsigned char* data, size_t len) +{ + string result; + size_t tailPos = len - 4; + char buffer[8]; + bool printable = false; + for (size_t i = 0; i < len; i++) { + if(i<=31 || i >= tailPos) { + if(!printable) { + if (i) + result.append(" "); + if (i && (i % 8) == 0) + result.append(" "); + if (i && (i % 16) == 0) + result.append(" "); + } + char curByte = data[i]; + if(curByte >= 32 && curByte <= 126) { + // Printable char + result+=curByte; + printable = true; + } else { + sprintf(buffer,"%02X",(unsigned char)curByte); + result.append(buffer); + printable = false; + } + } + if(i == 31) { + result+="... "; + } + } + return result; +} \ No newline at end of file diff --git a/log.h b/log.h index d532c42..68c408d 100644 --- a/log.h +++ b/log.h @@ -248,5 +248,7 @@ ATTR_FORMAT(2, 3) void Log(Severity severity, const char *format, ...); #undef ATTR_FORMAT #undef ATTR_NORETURN +std::string LogHexDump(const unsigned char* data, size_t len); + #endif From bb051ed2fc20265ba30ddfd183e7176d22a245a6 Mon Sep 17 00:00:00 2001 From: Frederic Borry Date: Tue, 8 Oct 2024 20:11:03 +0200 Subject: [PATCH 2/2] Fixed indentation. --- log.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/log.cpp b/log.cpp index 1febb8c..68b3da9 100644 --- a/log.cpp +++ b/log.cpp @@ -448,9 +448,12 @@ string LogHexDump(const unsigned char* data, size_t len) size_t tailPos = len - 4; char buffer[8]; bool printable = false; - for (size_t i = 0; i < len; i++) { - if(i<=31 || i >= tailPos) { - if(!printable) { + for (size_t i = 0; i < len; i++) + { + if(i<=31 || i >= tailPos) + { + if(!printable) + { if (i) result.append(" "); if (i && (i % 8) == 0) @@ -459,17 +462,21 @@ string LogHexDump(const unsigned char* data, size_t len) result.append(" "); } char curByte = data[i]; - if(curByte >= 32 && curByte <= 126) { + if(curByte >= 32 && curByte <= 126) + { // Printable char result+=curByte; printable = true; - } else { + } + else + { sprintf(buffer,"%02X",(unsigned char)curByte); result.append(buffer); printable = false; } } - if(i == 31) { + if(i == 31) + { result+="... "; } }