Printing integers in base 16

The output from the following code snippet is 8 digits long, as if it were a 32-bit variable:

int16_t x = -1;
Serial.println(x, HEX);

Bug or feature?

Feature

I've noticed that too. This will print the four hex digits:

 Serial.println((x&0xFFFF), HEX);

Perhaps the println function is only overloaded to handled int32_t when dealing with HEX.

Pete

el_supremo:
Perhaps the println function is only overloaded to handled int32_t when dealing with HEX.

That's right, although it isn't just HEX. But I was wondering if that is standard across C++ implementations or just an Arduino shortcut.

I worked around it by casting:

Serial.println((uint16_t)x, HEX);

AFAIK print and println aren't standard C++ features, they're specific to the Arduino IDE so they can implement it any way they see fit - even if it gives unexpected results :slight_smile:

Pete

el_supremo:
AFAIK print and println aren't standard C++ features, they're specific to the Arduino IDE so they can implement it any way they see fit - even if it gives unexpected results :slight_smile:

Pete

One can, of course, look at the HardwareSerial class, and see that it inherits the print() and println() methods from the Print class, and can look at how the Print class actually implements them.

I did that. Print explicitly casts an int as a long before doing a conversion to a number. I just wasn't sure if it was in the category of bug or not.