I'm trying to use the ATOI library function in C for Arduino to convert a string to an unsigned int. Out of all number data types I have chosen unsigned int as the number range does not need to be negative, and does not need a large positive number range. The highest would be 300000.
After researching I have found that the maximum number ATOI can spit out is 32767 before it then starts producing garbage (according to this forum post https://forum.arduino.cc/t/maximum-atoi-string/87722 ).
I have had a look around at some other library functions to handle a number of this size, but they seem to support other number data types (such as long, signed ect) but i'm a little oferwhelmed with one that would suit best, and just wanted to check here first to see if anyone else knew of a solution.
Thanks in advance.
The atoi
(family of functions) should never be used for any purpose, since they don't have proper error handling.
The strtol
(family of functions) should be used instead. It is equivalent except it has error handling and supports other bases than decimal as an option.
Furthermore, you seem unaware that AVR is using 16 bit integers, so an unsigned int
will only have the range 0 - 65535. If you need numbers up to 300000, you must use unsigned long
.
Therefore the function you are looking for is strtoul
from stdlib.h
. Usage:
#include <stdlib.h>
unsigned long x = strtoul(str, NULL, 10);
Please note that using the default "primitive data types" of C in embedded programming is naive. As you've noticed, they are nothing but trouble since their sizes aren't portable. Professional programmers always use stdint.h
types and never anything else. In this case uint32_t
.