Converting an int or String to a char array on Arduino

Chris picture Chris · Sep 12, 2011 · Viewed 306.2k times · Source

I am getting an int value from one of the analog pins on my Arduino. How do I concatenate this to a String and then convert the String to a char[]?

It was suggested that I try char msg[] = myString.getChars();, but I am receiving a message that getChars does not exist.

Answer

Peter Mortensen picture Peter Mortensen · Sep 12, 2011
  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.