Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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 the 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("
%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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 "
",a);
    printf("%" PRIu16 "
",b);
    return 0;
}

outputs:

1234
5678

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...