Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting a string to integer in C for arduino

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading