title: Endian Swap in C Union
body: <p>I am trying to understand the way an endian swap works when done within a union in C. I understand that a union has the ability to hold multiple types of data, but can only hold one type at a time. The code I am trying to understand looks like this, this is the union definition:</p>
  
  <pre><code>  union byte4 {
            char byte[4];
            int numint;
            float numfloat;
    };
  </code></pre>
  
  <p>This is the function.</p>
  
  <pre><code>  int endianSwap4int(int a) {
        union byte4 un;
        un.numint = a;
  
        // swap
        char c1 = un.byte[0];
        un.byte[0] = un.byte[3];
        un.byte[3] = c1;
        c1 = un.byte[1];
        un.byte[1] = un.byte[2];
        un.byte[2] = c1;
  
        return un.numint;
    }
  </code></pre>
  
  <p>In the function, if the input <code>a</code> is 2048327680, the function returns 6010 when <code>un.numint</code> is returned. I understand that manipulating <code>un.byte</code> is indirectly manipulating <code>un.numint</code> as well because unions can only hold one thing at a time, but I don't understand exactly how they affect each other, so my question is, how exactly do they affect each other?</p>