The correct way to convert char * numbers to int32_t

I want to convert a number from char * to a 32 bit integer int32_t, but strtol () returns long.

I do not know the long length of my car. It could be 32 or 64 bits or something else in the future.

What is the correct and bulletproof way to convert a string to a 32 bit integer int32_t? Or to convert long to int32_t.

Comparison with the _MAX and _MIN constants in the only and easiest way?

+5
source share
2 answers

Use sscanfwith one of the macro format specifier from <inttypes.h>, for example. SCNd32or SCNi32:

int32_t i;
sscanf(str, "%"SCNd32, &i);

They are available with the C99.

+10
source
char *buf;
long val;
....
if (1 == sscanf(buf, "%ld", &val) )
{
   // success!
   // now we have the data in a long, can do some boundary checking and then put it in an int32_t.
}
...
0
source

All Articles