Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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

share|improve this question
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
up vote 4 down vote accepted

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);

Will print it out correctly.

sprintf - http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

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

share|improve this answer
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.

share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.