3
\$\begingroup\$

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)

\$\endgroup\$
2

2 Answers 2

4
\$\begingroup\$

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.

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

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

Some implementations of the Print class, include printf (Like Adafruit's, see here). In that case, you just do Serial.printf("%04X", x).

\$\endgroup\$
2
  • \$\begingroup\$ Based on the source you linked, it seems that println( (unsigned) x ) will also work (casting to unsigned long rather than long). \$\endgroup\$ Commented Mar 23, 2013 at 17:56
  • \$\begingroup\$ Why did you allocated 9 bytes for buf variable when x fits under 5 bytes? \$\endgroup\$ Commented Jan 21, 2020 at 16:30
-2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 24, 2012 at 5:32
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 23, 2013 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.