Skip to content

String(unsigned long) constructor reverses digits, e.g. 10 becomes "01" #5585

@marcboon

Description

@marcboon

Arduino 1.8.15
ESP32 v2.0.0-rc-1
ESP32-S2-WROVER (Saola 1)

String() constructor from unsigned long reverses digits.
Code:

void setup() {
  Serial.begin(115200);
  delay(100);
    
  for(unsigned long ul = 0; ul < 25; ul++) {
    Serial.println(String(ul)); 
  }
}

void loop() {
}

Output:

0
1
2
3
4
5
6
7
8
9
01
11
21
31
41
51
61
71
81
91
02
12
22
32
42

After some more testing I found that the problem is actually with ultoa(), and also ltoa(). The String(unsigned long) constructor uses ultoa() for the conversion, while String(long) uses sprintf("%ld") when base is 10 (which works as expected), and ltoa() for other cases, which fail.
So, both ltoa() and ultoa() reverse digits.

  unsigned long value = 123456789;
  char buf[10];
  ultoa(value, buf, 10);
  Serial.print(buf);

produces "987654321"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions