title: How to convert struct to char array in C
body: <p>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.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  struct x
  {
     int x;
  } __attribute__((packed));
  
  
  int main()
  {
     struct x a;
     a.x=127;
     char *b = (char *)&amp;a;
     int i;
     for (i=0; i&lt;4; i++)
        printf("%02x ", b[i]);
     printf("\n");
     for (i=0; i&lt;4; i++)
        printf("%d ", b[i]);
     printf("\n");
     return 0;
  }
  </code></pre>
  
  <p>Here is the output for various values of a.x (on an X86 using gcc):<br>
  127:<br>
  7f 00 00 00 <br>
  127 0 0 0 <br></p>
  
  <p>128:<br>
  ffffff80 00 00 00<br>
  -128 0 0 0 <br></p>
  
  <p>255:<br>
  ffffffff 00 00 00 <br>
  -1 0 0 0 <br></p>
  
  <p>256:<br>
  00 01 00 00 <br>
  0 1 0 0 <br></p>
  
  <p>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</p>
  
  <p>Am I forgetting to do something in the conversion process or am I forgetting something about integer representation?</p>
  
  <p>*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. <br>
  *Edit: formatting</p>