13

I'm looking to convert an int value to a char array. currently I've found the following will return [number]

int num = [number]
str = String(num);
str.toCharArray(cstr,16);
Serial.println(cstr);

However, per Majenko's The Evils of Arduino Strings I feel like this code would make my Arduino's heap look like swiss cheese. Is there a better way to change an [int] into a char[n] array that avoids the String class?

ATE-ENGE
  • 903
  • 3
  • 19
  • 30

1 Answers1

14

itoa is the best route:

int num = 1234;
char cstr[16];
itoa(num, cstr, 10);
-> "1234"

You can read more about using it here.

If you want more control over the format of the number (and don't mind the increased PROGMEM usage) you can use sprintf (or the more secure snprintf) to format it:

sprintf(cstr, "%05d", num);
-> "01234"

Or with PROGMEM string constant:

sprintf_P(cstr, (PGM_P)F("%05d"), num);
-> "01234"

Or with more values:

sprintf_P(cstr, (PGM_P)F("%02d:%02d:%02d"), hours, minutes, seconds);
-> "03:23:11"
Majenko
  • 103,876
  • 5
  • 75
  • 133
  • Nice, I'm looking to take an int value in seconds and convert to hr:min:sec before I `strcat([c string],[time])` as I understand, I'll have to stick with `itoa` since I don't want it to go to serial? – ATE-ENGE Jul 24 '17 at 20:33
  • sprintf is a good choice. I'll add an example. – Majenko Jul 24 '17 at 20:33
  • Ok, that looks like it will work for me. how do you go about getting the `(PGM_P)F("%02d:%02d:%02d"),` section? (specifically the `(PGM_P)F` part) – ATE-ENGE Jul 24 '17 at 20:44
  • 1
    The F is documented in the arduino PROGMEM docs. The PGM_P just changes the pointer to the right type for_P variant functions. – Majenko Jul 24 '17 at 20:45
  • You can also use the PrintEX library to give you all the 'printf' capabilities without having to deal with string types. – starship15 May 03 '22 at 22:38