How can I convert from HEX to DECIMAL but keeping the leading 0s ?

      char input[9];

      String str = Serial1.readStringUntil((char)'B');
      String rf_id = str.substring(3, 11);
      Serial.println((String)"RFID HEX: '" + rf_id + "' - size: " + rf_id.length());

      rf_id.toCharArray(input, 9);
      int val = StrToHex(input);

I am reading an UID from a MIFARE card using an UART serial connection.

From the code above:
rf_id will be 0920A499
val will be 153134233 , but I need it to be 0153134233 .

At first I’ve tried using this answer as a base for my code: but Serial1 output is somewhat hard to parse and I am on an ESP32 so I don’t mind using String. It makes manipulating the data from Serial1 so much easier.

Since I know that the DECIMAL value must be expressed as a 10 digits number in the end (because 2^32 = 4 294 967 296 and because that’s how the respective RFID system does) I can transform val to a String and concatenate 0 to it until it has a length of 10.

      rf_id = String(val);
      while(rf_id.length() < 10)
        rf_id = "0" + rf_id;
      Serial.println((String)"RFID DEC: '" + rf_id + "' - size: " + rf_id.length());

Is there any other elegant way of doing this ? Keeping the leading 0s ?

Thank you.

Decimal numbers don't have a leading zero. What if there was 2 leading zeros.

Something like this perhaps

long val = 153134233;
char buffer[11];  //allow for terminating '\0'

void setup()
  while (!Serial);
  sprintf(buffer, "%010ld", val); //zero one zero lowercase L d
void loop()

I need it to be 0153134233


This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.