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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With