How to convert struct to char array in C

Posted by falcojr on Stack Overflow See other posts from Stack Overflow or by falcojr
Published on 2009-01-11T20:58:57Z Indexed on 2010/04/11 10:13 UTC
Read the original article Hit count: 313

Filed under:
|
|
|

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 <stdio.h>

struct x
{
   int x;
} __attribute__((packed));


int main()
{
   struct x a;
   a.x=127;
   char *b = (char *)&a;
   int i;
   for (i=0; i<4; i++)
      printf("%02x ", b[i]);
   printf("\n");
   for (i=0; i<4; i++)
      printf("%d ", b[i]);
   printf("\n");
   return 0;
}

Here is the output for various values of a.x (on an X86 using gcc):
127:
7f 00 00 00
127 0 0 0

128:
ffffff80 00 00 00
-128 0 0 0

255:
ffffffff 00 00 00
-1 0 0 0

256:
00 01 00 00
0 1 0 0

I understand the values for 127 and 256, but why do the numbers change when going to 128? Why wouldn't it just be: 80 00 00 00 128 0 0 0

Am I forgetting to do something in the conversion process or am I forgetting something about integer representation?

*Note: This is just a small test program. In a real program I have more in the struct, better variable names, and I convert to little-endian.
*Edit: formatting

© Stack Overflow or respective owner

Related posts about c

    Related posts about struct