Arduino String to int: How to convert a string into an integer. Find
out the standard function for this operation and learn how to code it
yourself.
Arduino string to int - find out:
The standard function for conversion.
The algorithm used for the process.
Exactly how to code it yourself.
Code for conversion of hexadecimal or binary strings.
You probably need to do some mathematical calculations using the
"numerical value" of the number string in your string, and the function
below allows you to do just that.
Arduino string to int: Standard form
The function you need is atoi() which has the prototype:
int atoi( char *str );
Where:
str - is a string buffer that stores the string.
The function takes the above arguments and returns an integer using base 10 (or decimal).
Note: unlike itoa(), atoi assumes a decimal radix string. But see atoir() that I wrote below to allow radix use.
The name of the function is an acronym for ASCII to int - atoi().
Where ASCII is another acronym standing for American Standard Code for Information Interchange. It defines is a table of characters.
Arduino string to int: Example
This example allows you to "add" two string numbers together
voidsetup(){
Serial.begin(115200);
int a,b,calc;
a = atoi("1234");
b = atoi("2345");
Serial.print("a+b= ");
calc = a+b;
Serial.println(calc);
if(calc==3579)
Serial.println("Adding strings successfull");
else
Serial.println("Adding strings FAILED");
}
voidloop(){
}
sketch: atoi_string_to_int_test.ino
Arduino: String to int Algorithm
The Arduino string to int code code is a lot simpler than itoa()
since the string length is fixed (set by user as the input string) and
the output type size is also fixed (integer). In addition the base used
is,... you guessed it... fixed at base 10 for decimal.
One complication is that the first character could be a minus sign.
So first store that information and move to the next character.
int sign = 0;
if (str[0]=='-') {
sign = 1;
str++'
}
To convert a string to a number start at the least value
digit and work backwards.
char *e = str + strlen(str)-1; // At end character.
Now build up the output value:
int v = 0;
int radix = 1;
while(e>=str) { // Has pointer moved before string start?
If the value of the character is not a digit then bail out returning zero
The code(*e - '0') gets the character value and changes it to a
number (0-9). This number us multiplied by the current position radix
value or decimal multiplier that increases x10 each time round the loop.
When pointer e
char *e = str + strlen(str) - 1; // At end character.
int v = 0;
int radix = 1;
while(e>=str){ // Has pointer moved before string start?
if( ! isdigit(*e))return0; // In ctype.h - Bail out!!!
v += (*e - '0') * radix;
e--; // Prev character.
radix *= 10;
}
if(sign) v=-v;
return v;
}
voidsetup(void){
int val;
Serial.begin(115200);
Serial.println("Arduino string to int...");
char num1[] = "123";
char num2[] = "12345";
val = _atoi(num1);
Serial.print("Num 1 "); Serial.println(num1);
Serial.print(" "); Serial.println(val);
val = _atoi(num2);
Serial.print("Num 2 "); Serial.println(num2);
Serial.print(" "); Serial.println(val);
Serial.print("Convert and add ");
val = _atoi(num1) + _atoi(num2);
Serial.print("val ");
Serial.println(val);
Serial.print("Should match ");
Serial.println(123+12345);
Serial.print("Check bad chars: ");
Serial.println(_atoi("123x"));
char num3[] = "-543";
Serial.print("Check negative: ");
Serial.println(_atoi(num3));
char num4[]="43";
Serial.print("Check(2) negative: ");
Serial.println(_atoi(num3)+_atoi(num4));
}
voidloop(void){
}
Arduino String to int: Output
Arduino string to int...
Num 1 123
123
Num 2 12345
12345
Convert and add val 12468
Should match 12468
Check bad chars: 0
Check negative: -543
Check(2) negative: -500
Arduino String to int: Adding radix conversion
This code allows you to convert numebers of differnent radix e.g. Hex or binary (or more).
char *e = str + strlen(str) - 1; // At end character.
int v = 0;
int radix = 1;
while(e>=str){ // Has pointer moved before string start?
int startChar = (*e<'9' ? '0' : 'A');
int adj = (*e>'9' ? 10 : 0); // Adjust number start
v += (toupper(*e) - startChar + adj) * radix;
e--; // Prev character.
radix *= base;
}
if(sign) v=-v;
return v;
}
voidsetup(void){
int val;
Serial.begin(115200);
Serial.println("Arduino string to int with RADIX...");
Serial.println("binary 101 op should be 5 ");
Serial.println(atoir("101", 2));
Serial.println("hex 11 o/p should be 17");
Serial.println(atoir("11", 16));
Serial.print("dec -27 o/p should be "); Serial.println((int)-27);
Serial.println(atoir("-27", 10));
Serial.print("hex 3f2 o/p should be "); Serial.println((int)0x3a2);
Serial.println(atoir("3A2", 16));
Serial.print("dec 12345 o/p should be "); Serial.println((int)12345);
Serial.println(atoir("12345", 10));
Serial.print("Bin 1010010110100101 = 0xa5a5 o/p should be ");
Serial.println((int)0xa5a5);
Serial.println(atoir("1010010110100101", 2));
}
voidloop(void){
}
Arduino String to int: Radix Output
Arduino string to int with RADIX...
binary 101 op should be 5
5
hex 11 o/p should be 17
17
dec -27 o/p should be -27
-27
hex 3f2 o/p should be 930
930
dec 12345 o/p should be 12345
12345
Bin 1010010110100101 = 0xa5a5 o/p should be -23131
-23131
Conclusions
The built in version - atoi() - works as expected; You can easily obtain an integer directly from a string.
You have learned, from this page, how to code the Arduino string to int function - _atoi() - from first principles.
TIP: Use atoi() to convert a decimal string to an integer.
On this page you have also found out how to code a non standard
function that converts a string of different radix (i.e.different to 10)
into an integer - that can convert a hexadecimal or binary string to a base-10 number:
atoir()
TIP: Use atoir() to convert hexadecimal or binary strings to integers.
Written by John Main, who has a degree in Electronic Engineering.
How to get accurate DHT22 digital humidity sensor readings with an Arduino. Did you know it also measures temperature as Well? Find out why, in this page...
A PIR sensor lets your Arduino sense movement without contact. This tutorial covers PIR sensor basics, connecting one to an Arduino board and coding a motion detector.
Arduino Hall Effect Sensor: Add magnetic sensing superpowers to your Arduino projects with an easy-to-use hall effect sensor. With full code and layout...
Comments
Have your say about what you just read! Leave me a comment in the box below.
Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.