printf u_int32_t

I've been scratching my head for a while now, I can't see to get printf to print out a u_int32_t value correctly, I've been using %c but it does not yield the correct value. Can anyone tell me the correct option?

thanks
 
Quick note up front, uint32_t and the like are preferred to u_int32_t nowadays.

You have several choices, depending on how you value code readability versus portability to ancient or strange systems.

If readability is most important, then use %u. This works if uint32_t is the same as unsigned int (most current platforms, including FreeBSD on all supported architectures) or if uint32_t is smaller than unsigned int. In the former case, the type matches exactly; in the latter case, the value is promoted to an int with a positive value which can safely be read as an unsigned int.

If the code has to run on platforms with 16-bit int, you can use the macros from <inttypes.h> like

Code:
printf("x=%"PRIu32"\n", x);

or cast the value to a suitable type such as unsigned long and use the matching formatting specification for that type (such as %lu). Note that C99 requires long to be at least 32 bits but if the system is so strange that you need this it may not comply to that part.

If this is for FreeBSD code, it is OK to assume that int is at least 32 bits and the macros from <inttypes.h> should be avoided as many developers do not like them. Also use the j, t and z length modifiers where appropriate.
 
Back
Top