i'm looking for the standard functions to convert a string to an stdint.h integer, like
int i = atoi("123");
unsigned long ul = strtoul("123", NULL, 10);
uint32_t n = mysteryfunction("123"); // <-- ???
There are two general options: strto[iu]max
followed by a check to see if the value fits in the smaller type, or switch to sscanf
. The C standard defines an entire family of macros in <inttypes.h>
that expand to the appropriate conversion specifier for the <stdint.h>
types. Example for uint32_t
:
#include <inttypes.h>
#include <stdio.h>
int main()
{
uint32_t n;
sscanf("123", "%"SCNu32, &n);
printf("%"PRIu32"\n", n);
return 0;
}
(In the case of uint32_t
, strtoul
+ overflow check would also work for uint32_t
because unsigned long
is at least 32 bits wide. It wouldn't reliably work for uint_least32_t
, uint_fast32_t
, uint64_t
etc.)
Edit: as Jens Gustedt notes below, this doesn't offer the full flexibility of strtoul
in that you can't specify the base. However, base 8 and base 16 are still possible to obtain with SCNo32
and SCNx32
, respectively.
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