Convert char* to unsigned int

Hello,

i'm trying to convert a char* which contains 50770 value to integer.

If i use atoi() then i get -14766
if i use cast conversion uint16_t() then i get 1617
if i use cast int() conversion then i get 1904

i want 50770 as int.

Can anyone help me?

i want 50770 as int

Do you mean an int, an integer or maybe an unsigned int ?

An int on the Arduino has a maximum value of 32,767. An unsigned int has a maximum value of 65,535

try atol and store the result in a long

meetjeremy:
Hello,

i'm trying to convert a char* which contains 50770 value to integer.

If i use atoi() then i get -14766
if i use cast conversion uint16_t() then i get 1617
if i use cast int() conversion then i get 1904

i want 50770 as int.

Can anyone help me?

I'm assuming you have a character string with those digits?

If you have this:

char *number_string = "50770";

you need to do this to get it as an int:

char *number_string = "50770";
unsigned int value = atoi (number_string);  // notice UNSIGNED int
// now "value" is the integer 50770

The reason you were getting -14766 is that you tried to atoi the string into an int (which is SIGNED). An Arduino int is 16 bits, so the value "50770" stored as a 16 bit signed integer is 50770 - 65536 = -14766. Using an unsigned int allows you to get any number from 0 to 65535. For larger numbers, use a long int (or unsigned long int).

Just FYI, if you instead had a floating point number, you would use atof(), like this:

char *number_string = "123.4567";
float value = atof (number_string);

For that matter, you could use atof() on your integer string, but you would get back the floating point value "50770.000" rather than the integer "50770".

Hope this makes sense.

1 Like

Hello All,

Thanks for you help guys . It worked.

Thanks Krupski for detailed Explanation.