[c] How do I print uint32_t and uint16_t variables value?

I am trying to print an uint16_t and uint32_t value, but it is not giving desired output.

#include <stdio.h>
#include <netinet/in.h>

int main()
{
     uint32_t a=12,a1;
     uint16_t b=1,b1;
     a1=htonl(a);
     printf("%d---------%d",a1);
     b1=htons(b);
     printf("\n%d-----%d",b,b1);
     return 0;
}

I also used

 printf("%"PRIu32, a);

which is showing an error.

How do I print these values and what will be the desired output?

This question is related to c gcc

The answer is


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.