How to convert struct to char array in C

前端 未结 10 540
孤城傲影
孤城傲影 2020-12-19 03:00

I\'m trying to convert a struct to a char array to send over the network. However, I get some weird output from the char array when I do.

#include 

        
10条回答
  •  心在旅途
    2020-12-19 03:32

    The x format specifier by itself says that the argument is an int, and since the number is negative, printf requires eight characters to show all four non-zero bytes of the int-sized value. The 0 modifier tells to pad the output with zeros, and the 2 modifier says that the minimum output should be two characters long. As far as I can tell, printf doesn't provide a way to specify a maximum width, except for strings.

    Now then, you're only passing a char, so bare x tells the function to use the full int that got passed instead — due to default argument promotion for "..." parameters. Try the hh modifier to tell the function to treat the argument as just a char instead:

    printf("%02hhx", b[i]);
    

提交回复
热议问题