# Arduino: why does Serial.println(int, HEX) display 4 bytes?

An int is 2 bytes but Serial.print with HEX or BIN formatting outputs 4 bytes:

  int x = 0x9876;
Serial.println(x, HEX);
// output is FFFF9876


Why?

(and what is a good way to print out only 2 bytes)

-
This question would be a better fit for Stack Overflow possibly with the "embedded" tag. –  embedded.kyle Nov 27 '12 at 21:43
Ok, thanks. I wasn't sure which site was best. –  Brian Low Nov 29 '12 at 5:22
It's a fine line. See here: meta.electronics.stackexchange.com/questions/2457/… –  embedded.kyle Nov 29 '12 at 13:12

The Arduino print / println function casts the int to a long, which is 4 bytes long for Arduinos. See here: https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/Print.cpp

To have more control over printing check out the C++ sprintf function. For example,

int x = 0x9876;
char buf[9];
sprintf(buf, "%04x", x);
Serial.println(buf);


Will print it out correctly.

format string reference - http://www.cplusplus.com/reference/clibrary/cstdio/printf/

-
Based on the source you linked, it seems that println( (unsigned) x ) will also work (casting to unsigned long rather than long). –  greggo Mar 23 '13 at 17:56

This is because the data-type 'int' in 'C' language, as per ANSI C standards, is a 32-bit numeric type, and thus you see 4 bytes.

If your variable 'x' can only take 2 byte values, then declare it as a 'short' variable, instead of 'int'. This is because 'short' type as per the language standards is a 16-bit numeric type.

-
Arduino ints are 16 bits. According to answers here stackoverflow.com/questions/589575/size-of-int-long-etc the C standard says ints have to be able to represent from -32767 to 32767, which is possible in 16 bits. –  geometrikal Nov 24 '12 at 5:32
Correct ints are 16, the problem as pointed out by geometrikal is that println converts all to longs (32) and println( int ) converts to long. println( unsigned ) will convert to unsigned long, and should do what the OP is expecting. –  greggo Mar 23 '13 at 18:00