what's the equivalent of atoi or strtoul for uint32_t and other stdint types?

Christophe Priieur picture Christophe Priieur · Apr 21, 2011 · Viewed 7.6k times · Source

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"); // <-- ???

Answer

Fred Foo picture Fred Foo · Apr 21, 2011

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.