Skip to content

Commit a4f6875

Browse files
committed
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.
1 parent 0f4e57e commit a4f6875

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

api/Print.cpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,22 +238,36 @@ size_t Print::println(const Printable& x)
238238

239239
// Private Methods /////////////////////////////////////////////////////////////
240240

241-
size_t Print::printNumber(unsigned long n, uint8_t base)
241+
size_t Print::printNumber(unsigned long n, uint16_t base)
242242
{
243243
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
244244
char *str = &buf[sizeof(buf) - 1];
245245

246246
*str = '\0';
247247

248+
uint8_t minDigits = 1;
249+
uint8_t maxDigits = sizeof(buf) - 1;
250+
if (base > 0xFF)
251+
{
252+
minDigits = base >> 8;
253+
base = base & 0xFF;
254+
}
255+
if (minDigits > maxDigits) minDigits = maxDigits;
256+
248257
// prevent crash if called with base == 1
249258
if (base < 2) base = 10;
250259

260+
uint8_t usedDigits = 0;
251261
do {
252262
char c = n % base;
253263
n /= base;
254264

255265
*--str = c < 10 ? c + '0' : c + 'A' - 10;
266+
usedDigits++;
256267
} while(n);
268+
while (usedDigits++ < minDigits) {
269+
*--str = '0';
270+
}
257271

258272
return write(str);
259273
}

api/Print.h

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,25 @@
2626
#include "Printable.h"
2727

2828
#define DEC 10
29-
#define HEX 16
29+
#define HEX 0x0010
30+
#define HEX2 0x0210
31+
#define HEX4 0x0410
32+
#define HEX8 0x0810
3033
#define OCT 8
31-
#define BIN 2
34+
#define BIN 0x0002
35+
#define BIN2 0x0202
36+
#define BIN4 0x0402
37+
#define BIN8 0x0802
38+
#define BIN16 0x1002
39+
#define BIN32 0x2002
3240

3341
namespace arduino {
3442

3543
class Print
3644
{
3745
private:
3846
int write_error;
39-
size_t printNumber(unsigned long, uint8_t);
47+
size_t printNumber(unsigned long, uint16_t);
4048
size_t printULLNumber(unsigned long long, uint8_t);
4149
size_t printFloat(double, int);
4250
protected:

0 commit comments

Comments
 (0)