Arduino How to Convert int to String Easily
In Arduino, convert an int to a string by using
String(yourInt) or the itoa() function to store the result in a char array.Examples
Input123
Output"123"
Input0
Output"0"
Input-456
Output"-456"
How to Think About It
To convert an integer to a string in Arduino, think about turning the number into readable text. You can use the built-in
String() function for a quick conversion or use itoa() to fill a character array with the number's digits as text.Algorithm
1
Take the integer value you want to convert.2
Use the <code>String()</code> function or <code>itoa()</code> to convert the integer to a string format.3
Store or print the resulting string as needed.Code
arduino
void setup() { Serial.begin(9600); int number = 123; String strNumber = String(number); Serial.println(strNumber); } void loop() { // Nothing here }
Output
123
Dry Run
Let's trace converting the integer 123 to a string using String()
1
Start with integer
number = 123
2
Convert using String()
strNumber = String(123) -> "123"
3
Print the string
Serial.println("123") outputs 123
| Step | Variable | Value |
|---|---|---|
| 1 | number | 123 |
| 2 | strNumber | "123" |
| 3 | Serial output | 123 |
Why This Works
Step 1: Using String()
The String() function takes an integer and creates a new string object representing that number.
Step 2: Printing the string
When you print the string, Arduino sends the characters one by one to the serial monitor.
Alternative Approaches
Using itoa() function
arduino
void setup() { Serial.begin(9600); int number = 123; char buffer[10]; itoa(number, buffer, 10); Serial.println(buffer); } void loop() { // Nothing here }
This method uses a character array and is more memory efficient than String objects.
Using sprintf() function
arduino
void setup() { Serial.begin(9600); int number = 123; char buffer[10]; sprintf(buffer, "%d", number); Serial.println(buffer); } void loop() { // Nothing here }
sprintf() formats the integer into a string, useful for complex formatting but uses more memory.
Complexity: O(n) time, O(n) space
Time Complexity
Conversion time depends on the number of digits (n) in the integer, as each digit is processed.
Space Complexity
Extra space is needed to store the string representation, proportional to the number of digits.
Which Approach is Fastest?
Using itoa() is faster and uses less memory than String(), which creates objects dynamically.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String() | O(n) | O(n) | Simple and quick code |
| itoa() | O(n) | O(n) | Memory-efficient and faster |
| sprintf() | O(n) | O(n) | Formatted strings, more complex |
Use
String() for quick conversions and itoa() for memory-efficient code.Trying to assign an int directly to a String variable without conversion causes errors.