Sub topic 5
Formatting numbers: DEC, HEX, BIN, and decimal places
This chapter assumes you can upload a sketch, that Serial.begin() is already in your setup(), and that you know the difference between int, long, byte, and float in C/C++. It covers the optional second argument of Serial.print() and Serial.println(), which controls how a number appears in the Serial Monitor.
Why formatting matters
A value in memory has no base. The int holding 42 is a pattern of bits. How it looks on screen depends on the text that Serial.print() produces from it. By default, integers print in decimal. Often another view is more useful:
- Hexadecimal (base 16) matches register values, I2C addresses, memory dumps, and color codes.
- Binary (base 2) shows which individual bits of a port, flag byte, or sensor register are set.
- A fixed number of decimal places keeps floating-point readings readable and lines of output aligned.
The second argument
Both print() and println() accept an optional second argument.
Serial.print(value, format);
Serial.println(value, format);The meaning of format depends on the type of value.
| Value type | Second argument | Meaning |
|---|---|---|
| Integer types (`int`, `long`, `byte`, and so on) | `DEC`, `HEX`, `BIN`, `OCT`, or a number from 2 to 36 | The number base |
| `float` or `double` | An integer, such as `2` | Digits after the decimal point |
DEC, HEX, BIN, and OCT are constants defined by the Arduino core. They equal 10, 16, 2, and 8, so Serial.print(42, 16) behaves the same as Serial.print(42, HEX). The named constants are easier to read.
Integers in different bases
This sketch prints one value in several formats.
void setup() {
Serial.begin(9600);
Serial.println(42); // 42
Serial.println(42, HEX); // 2A
Serial.println(42, BIN); // 101010
Serial.println(3.14159, 2); // 3.14
}
void loop() {
}Open the Serial Monitor at 9600 baud and press the board's reset button if you missed the output. The setup code runs once at power-up or reset, so the lines appear only once.
Three details about the output are easy to miss:
- Hex digits above 9 print as uppercase letters (
2A, not2a). - No prefix is added.
42, HEXprints2A, not0x2A. You must print the0xorByourself if you want it. - Leading zeros are not printed.
5in binary prints as101, not00000101.
Adding a prefix
To make the base obvious, print the prefix as a separate item.
void setup() {
Serial.begin(9600);
byte status = 5;
Serial.print(F("status = 0x"));
Serial.print(status, HEX);
Serial.print(F(" = 0b"));
Serial.println(status, BIN);
}
void loop() {
}This prints status = 0x5 = 0b101.
Padding with leading zeros
Leading zeros matter when you read bit patterns, because you compare columns. Serial.print() has no padding option, so you add it with a loop. The next sketch pads a byte to eight binary digits.
void printBinary8(byte value) {
for (int bit = 7; bit >= 0; bit--) {
Serial.print(bitRead(value, bit));
}
}
void setup() {
Serial.begin(9600);
byte flags = 5;
Serial.print(F("flags = 0b"));
printBinary8(flags);
Serial.println();
}
void loop() {
}This prints flags = 0b00000101. bitRead(value, bit) returns 0 or 1 for the chosen bit, and the loop walks from bit 7 (most significant) down to bit 0.
A similar helper pads hex to two digits:
void printHex2(byte value) {
if (value < 0x10) {
Serial.print('0');
}
Serial.print(value, HEX);
}
void setup() {
Serial.begin(9600);
byte data[] = {0x0A, 0xFF, 0x03};
for (int i = 0; i < 3; i++) {
printHex2(data[i]);
Serial.print(' ');
}
Serial.println();
}
void loop() {
}This prints 0A FF 03 . Without the helper, the output would be A FF 3, which is harder to read as a byte dump.
Negative numbers and the size of the type
Signed integers behave differently across bases, and this is a common source of confusion.
- In
DEC, a negativeintprints with a minus sign:-1. - In
HEX,BIN, andOCT, the board prints the raw bit pattern. On an Uno, whereintis 16 bits,-1prints asFFFF. On a 32-bit board such as the ARM-based Arduino Zero or the ESP32,intis 32 bits and-1prints asFFFFFFFF.
void setup() {
Serial.begin(9600);
int n = -1;
Serial.println(n); // -1
Serial.println(n, HEX); // FFFF on an Uno, FFFFFFFF on 32-bit boards
Serial.println((byte)n, HEX); // FF on every board
}
void loop() {
}The size of the value you pass decides how many digits you get. If you want exactly the eight bits of a register, cast to byte first. That also removes the board dependence.
Which types to choose
| Type | Size on an Uno | Largest hex output |
|---|---|---|
| `byte` / `uint8_t` | 8 bits | `FF` |
| `int` / `uint16_t` | 16 bits | `FFFF` |
| `long` / `uint32_t` | 32 bits | `FFFFFFFF` |
Characters are not numbers when printed
A char or a byte can seem interchangeable, but print() treats them differently by default. A char prints as a character. A byte prints as a number.
void setup() {
Serial.begin(9600);
char c = 'A';
byte b = 65;
Serial.println(c); // A
Serial.println(b); // 65
Serial.println(c, DEC); // 65
Serial.println(b, HEX); // 41
}
void loop() {
}If you want the numeric code of a char, pass DEC or HEX as the second argument. This is useful when you are debugging serial input and want to see invisible characters such as the newline (code 10) and carriage return (code 13).
Decimal places for floats
For a float, the second argument is the number of digits after the decimal point. The default is 2.
void setup() {
Serial.begin(9600);
float pi = 3.14159265;
Serial.println(pi); // 3.14
Serial.println(pi, 0); // 3
Serial.println(pi, 1); // 3.1
Serial.println(pi, 4); // 3.1416
}
void loop() {
}The value is rounded, not cut off, so 3.14159 with four places prints 3.1416.
Precision limits
Asking for more digits does not create more precision. On AVR boards such as the Uno and Nano, float and double are both 32-bit and carry about 6 to 7 significant digits. Printing more places shows noise, not accuracy.
void setup() {
Serial.begin(9600);
float x = 1.0 / 3.0;
Serial.println(x, 2); // 0.33
Serial.println(x, 6); // 0.333333
Serial.println(x, 10); // trailing digits are not meaningful
}
void loop() {
}Pick a number of places that fits the real resolution of the data. A 10-bit analog reading on a 5 V board changes in steps of about 0.005 V, so two or three decimals is enough.
Very large and special values
Two limits are worth knowing:
- On AVR boards,
print()for floats does not use scientific notation. Very large values print asovf(overflow), and invalid results print asnanorinf. - A
NaNfrom an operation like0.0 / 0.0prints asnan. Seeingnanorinfin the monitor tells you a calculation divided by zero or overflowed.
Using the formats on real data
The sketch below reads an analog pin and prints the same number in three forms plus the computed voltage. It assumes a 5 V board such as the Uno.
const int SENSOR_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(SENSOR_PIN);
float volts = raw * (5.0 / 1023.0);
Serial.print(F("DEC="));
Serial.print(raw);
Serial.print(F(" HEX=0x"));
Serial.print(raw, HEX);
Serial.print(F(" BIN=0b"));
Serial.print(raw, BIN);
Serial.print(F(" V="));
Serial.println(volts, 2);
delay(500);
}A typical line looks like DEC=512 HEX=0x200 BIN=0b1000000000 V=2.50. The raw value is 10 bits, so the binary output has up to 10 digits and shorter values lose their leading zeros.
Common errors
- Expecting a base prefix.
Serial.print(255, HEX)givesFF, not0xFF. Print the prefix separately. - Passing a base to a float.
Serial.print(3.5, HEX)does not give a hex float. The2inSerial.print(x, 2)always means decimal places for a float. - Assuming an
intis 16 bits. Negative numbers inHEXshow different lengths on different boards. Cast to a fixed-width type such asuint16_twhen it matters. - Printing a
charand expecting a number. UseDECas the second argument, or cast toint. - Over-long decimals. Printing eight places of a
floatshows rounding error, not data. - Integer division before printing.
Serial.println(5 / 2, 2)prints2.00because5 / 2is integer division and gives 2. Write5.0 / 2to get2.50.
How the formats relate
The diagram shows how one stored value reaches the screen in each format.
Exercises
Exercise
A byte variable holds the value 9. What does Serial.println(value, BIN) print, and how would you make it print 00001001?
Show answer
It prints 1001, because leading zeros are not printed. To get 00001001, loop from bit 7 down to bit 0 and print bitRead(value, bit) for each bit, as in the printBinary8() helper.
Exercise
On an Arduino Uno, int n = -2; is printed with Serial.println(n, HEX). What is the output, and what would you change to get a board-independent result?
Show answer
The output is FFFE, the 16-bit two's complement pattern of -2. On a 32-bit board it would be FFFFFFFE. Cast to a fixed-width type, for example Serial.println((uint8_t)n, HEX) prints FE on every board.
Exercise
What does Serial.println(7 / 2, 3) print, and why? Change the expression so it prints 3.500.
Show answer
It prints 3.000... only if the division is done in floating point. Here 7 / 2 is integer division and gives 3, so the float conversion shows 3.000. Write 7.0 / 2 to get 3.500.