ArduinoCore-API icon indicating copy to clipboard operation
ArduinoCore-API copied to clipboard

Serial.print(x, BIN) doesn't print correct binary values for int8_t type

Open qub1750ul opened this issue 9 years ago • 2 comments

Screenshot

qub1750ul avatar Sep 12 '16 15:09 qub1750ul

https://github.com/arduino/Arduino/issues/4460 has a similar discussion to this, but regarding Serial.print(x, HEX);

sandeepmistry avatar Sep 12 '16 15:09 sandeepmistry

Short answer: don't use print(x, base) with signed values that may be negative; cast explicitly to an unsigned type first:

Serial.print((uint8_t)x, BIN);

Discussion: were you expecting this function to display -1010, or 11110110? The current implementation is a bit strange (in my opinion) in that base 10 is a special case that can print negative values, whereas any other base converts to unsigned long (regardless of length) and ignores the sign. Personally I think that -1010 would be the "mathematically correct" binary representation of -10 (and the one Python's bin() and JavaScript's .toString(2) use). This behavior would be very easy to implement as it only involves deleting a couple of lines (see PR arduino/Arduino#4535). The other option, make print(x, base) convert to an unsigned type of the same size as the argument looks a bit more complex (it would involve adding the check to see if base is 10 to all the integer versions of print), plus in my opinion is inconsistent since it treats base 10 specially.

In short, I think the current behavior of print with a base and negative numbers is "surprising" and should be corrected so that it does one of the two things I commented. I vote for the first one.

cousteaulecommandant avatar Dec 31 '16 18:12 cousteaulecommandant