How to convert struct to char array in C

前端 未结 10 514
孤城傲影
孤城傲影 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:19

    What you see is the sign preserving conversion from char to int. The behavior results from the fact that on your system, char is signed (Note: char is not signed on all systems). That will lead to negative values if a bit-pattern yields to a negative value for a char. Promoting such a char to an int will preserve the sign and the int will be negative too. Note that even if you don't put a (int) explicitly, the compiler will automatically promote the character to an int when passing to printf. The solution is to convert your value to unsigned char first:

    for (i=0; i<4; i++)
       printf("%02x ", (unsigned char)b[i]);
    

    Alternatively, you can use unsigned char* from the start on:

    unsigned char *b = (unsigned char *)&a;
    

    And then you don't need any cast at the time you print it with printf.

提交回复
热议问题