The standard C library does not have a strtoint32()
.
I want to convert a string ... to a 32-bit int.
I know of strtol
and strtoimax
, but these seem to return 64-bit ints.
There is long strtol()
that certainly meets OP's needs. It forms an integer at least 32-bits. Use it and additional tests if needed.
#include <ctype.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
// really no need for this:
// typedef int32_t Int32;
// Int32 strToIntValue(char* str) {
int32_t strToIntValue(const char* str) {
char* end;
errno = 0;
long num = strtol(str, &end, 10);
if (num == end) {
printf("No conversion error!\n");
return 0;
}
#if LONG_MAX > INT32_MAX
if (num > INT32_MAX) {
num = INT32_MAX;
errno = ERANGE;
}
#endif
#if LONG_MIN < INT32_MIN
if (num < INT32_MIN) {
num = INT32_MIN;
errno = ERANGE;
}
#endif
if (errno==ERANGE) {
printf("range error!\n");
return 0;
}
// Maybe check for trailing non-white space?
while (isspace((unsigned char) *end) {
end++;
}
if (*end) {
printf("Trailing junk!\n");
return 0;
}
// else {
return (int32_t) num;
//}
}
Consider printing error output to stderr
rather than stdout
.
// printf("range error!\n");
fprintf(stderr, "range error!\n");
See Why is there no strtoi in stdlib.h? for more ideas.