String(val, base) not converting decimals to binary correctly?

Newbie here. I've been trying to convert strings to binary using the String() command and it's not converting correctly?

void setup() {
 Serial.begin(9600);
 String test = String(13,BIN);
 Serial.println(test);
}

The code above^ will have an output of 1111, but the output should be 1101 (the arduino documentation also confirms that the output should be 1101 String() - Arduino Reference ).

p.s sorry for bad english

Nope.
The code below is basically identical, but with a non-ancient baud rate, and shows that.

void setup() {
  Serial.begin(115200);
  String test = String(13, BIN);
  Serial.println(test);
}
void loop() {}
14:43:12.404 -> 1101
1 Like

....I'm stupid. I tried my code in tinkercad and it showed 1111. But I just tried using an actual arduino and it showed the correct value of 1101. Thanks...

Edit: I guess it's a tinkercad error instead of an arduino one.

Try using https://wokwi.com Much better IMO.

1 Like

Nice. Thanks!

If you intend to program ordinary Arduinos like UNO, Nano, Micro, Mini or Mega,
you better don't invest any time in the String data type.

Using it leads you with its convenience functions to blocking I/O,
and creates a good chance of memory problems after longer runtimes,
if not used very carefully.

You can skip these experiences by avoiding String,
unless you have plenty of RAM like in an ESP32 environment. :grinning:

1 Like