Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"); // <-- ???
like image 767
Christophe Priieur Avatar asked Apr 21 '11 14:04

Christophe Priieur


1 Answers

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.

like image 198
Fred Foo Avatar answered Sep 28 '22 09:09

Fred Foo