Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to convert char * number to int32_t

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

I don't know length of long on my machine. It could be 32 or 64 bit or something else in the future.

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

Is comparison to _MAX and _MIN constants the only and most simple way?

like image 976
Marko Kevac Avatar asked Nov 17 '11 12:11

Marko Kevac


1 Answers

Use sscanf with one of the format specifier macros from <inttypes.h>, e.g. SCNd32 or SCNi32:

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

These are available since C99.

like image 82
Fred Foo Avatar answered Nov 12 '22 02:11

Fred Foo