How do I print uint32_t and uint16_t variables' value?
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
The macros defined in <inttypes.h>
are the most correct way to print values of types uint32_t
, uint16_t
, and so forth -- but they're not the only way.
Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf
format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)
An alternative is to cast the values to a predefined type and use the format for that type.
Types int
and unsigned int
are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t
or uint16_t
, respectively. Similarly, long
and unsigned long
are at least 32 bits wide, and long long
and unsigned long long
are at least 64 bits wide.
For example, I might write your program like this (with a few additional tweaks):
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t a=12, a1;
uint16_t b=1, b1;
a1 = htonl(a);
printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
b1 = htons(b);
printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
return 0;
}
One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>
. Such an implementation most likely wouldn't have <stdint.h>
either, but the technique is useful for other integer types.