From a4f6875eea595b8b945e6ac5cf83dcdaf2874df5 Mon Sep 17 00:00:00 2001 From: Tobias Knauss Date: Mon, 27 Apr 2026 20:00:36 +0200 Subject: [PATCH] more print format constants defined; function printNumber(..) adapted. - HEX2, HEX4, HEX8 - BIN2, BIN4, BIN8, BIN16, BIN32 The number represents the minimum digit count for printing, i.e. adding leading zeros. --- api/Print.cpp | 16 +++++++++++++++- api/Print.h | 14 +++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/api/Print.cpp b/api/Print.cpp index 4a6e942a..ee6d3b83 100644 --- a/api/Print.cpp +++ b/api/Print.cpp @@ -238,22 +238,36 @@ size_t Print::println(const Printable& x) // Private Methods ///////////////////////////////////////////////////////////// -size_t Print::printNumber(unsigned long n, uint8_t base) +size_t Print::printNumber(unsigned long n, uint16_t base) { char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. char *str = &buf[sizeof(buf) - 1]; *str = '\0'; + uint8_t minDigits = 1; + uint8_t maxDigits = sizeof(buf) - 1; + if (base > 0xFF) + { + minDigits = base >> 8; + base = base & 0xFF; + } + if (minDigits > maxDigits) minDigits = maxDigits; + // prevent crash if called with base == 1 if (base < 2) base = 10; + uint8_t usedDigits = 0; do { char c = n % base; n /= base; *--str = c < 10 ? c + '0' : c + 'A' - 10; + usedDigits++; } while(n); + while (usedDigits++ < minDigits) { + *--str = '0'; + } return write(str); } diff --git a/api/Print.h b/api/Print.h index 2016d7d5..38fdd9c9 100644 --- a/api/Print.h +++ b/api/Print.h @@ -26,9 +26,17 @@ #include "Printable.h" #define DEC 10 -#define HEX 16 +#define HEX 0x0010 +#define HEX2 0x0210 +#define HEX4 0x0410 +#define HEX8 0x0810 #define OCT 8 -#define BIN 2 +#define BIN 0x0002 +#define BIN2 0x0202 +#define BIN4 0x0402 +#define BIN8 0x0802 +#define BIN16 0x1002 +#define BIN32 0x2002 namespace arduino { @@ -36,7 +44,7 @@ class Print { private: int write_error; - size_t printNumber(unsigned long, uint8_t); + size_t printNumber(unsigned long, uint16_t); size_t printULLNumber(unsigned long long, uint8_t); size_t printFloat(double, int); protected: