title: Converting big endian structures to little endian
body: <p>I'm making a C program that communicates with a patient monitor that uses big endian byte ordering. For example, if I've certain C structure </p>
  
  <pre><code>typedef struct {
     int short a;
     int short b;
     int       c;
  } msg;
  </code></pre>
  
  <p>To read this kind of structure, I can simply use ntohs(msg.a), ntohs(msg.b), ntohl(msg.c). But some of the structure has a buffer of short integers but that buffer itself is type of an another structure. For example,</p>
  
  <pre><code>typedef struct {
     int short length;
     int short b[MAX_BUF_SIZE];
  } msg1;
  </code></pre>
  
  <p>The field "b" in above structure represents an another structure, which is below:</p>
  
  <pre><code>typedef struct {
     int short a;
     int short b;
  } msg2;
  </code></pre>
  
  <p>Now, my question is 1) should I convert all the short integers of structure "msg1" to host order and then cast it to pointer of type "msg2" and simply read "msg2.a" and "msg2.b" or 2) I should convert the byte ordering of "msg2.a" and "msg2.b" as well or 3) just cast 
  "msg1.b" to pointer of type "msg2" and read "msg2.a" and "msg2.b" by converting each of them to host order?</p>
  
  <p>Please tell which one of the approach is correct to read msg1</p>
  
  <h2>APPROACH 1</h2>
  
  <pre><code>int t[msg1.length];
  for(int i = 0; i &lt; msg1.length; i++)
     t[i] = ntohs(*(msg1.b + i));
  msg2 * msg2_m = (msg2 *)t;
  /* should I convert the msg2_m.a and msg2_m.b as well? */
  printf("%d:%d", msg2_m.a, msg2_m.b);
  </code></pre>
  
  <h2>APPROACH 2</h2>
  
  <p>All same except</p>
  
  <pre><code>printf("%d:%d", ntohs(msg2_m.a), ntohs(msg2_m.b));
  </code></pre>
  
  <h2>APPROACH 3</h2>
  
  <p>Not converting "msg1.b" and directly casting "msg1.b" to "msg2" and just convert "msg2.a" and "msg2.b" to host order.</p>
  
  <pre><code>msg2 *msg2_m = (msg2 *)msg1.a;
  printf("%d:%d", ntohs(msg2_m.a), ntohs(msg2_m.b));
  </code></pre>
  
  <p>I need to understand when a structure is casted to some other structures does its byte ordering are changed according to the new structure when passed across network? I think APPROACH 3 is correct, but thats just me, I'm not sure about internals of byte ordering. Any help would be appreciated.</p>
  
  <p>Thanks,
  Shivam Kalra</p>