title: Integer Byte Swapping in C++
body: <p>I'm working on a homework assignment for my C++ class. The question I am working on reads as follows:</p>
  
  <blockquote>
    <p>Write a function that takes an unsigned short int (2 bytes) and swaps the bytes. For example, if the x = 258 ( 00000001 00000010 ) after the swap, x will be 513 ( 00000010 00000001 ).</p>
  </blockquote>
  
  <p>Here is my code so far:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  unsigned short int ByteSwap(unsigned short int *x);
  
  int main()
  {
    unsigned short int x = 258;
    ByteSwap(&amp;x);
  
    cout &lt;&lt; endl &lt;&lt; x &lt;&lt; endl;
  
    system("pause");
    return 0;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>unsigned short int ByteSwap(unsigned short int *x)
  {
    long s;
    long byte1[8], byte2[8];
  
    for (int i = 0; i &lt; 16; i++)
    {
      s = (*x &gt;&gt; i)%2;
  
      if(i &lt; 8)
      {
        byte1[i] = s;
        cout &lt;&lt; byte1[i];
      }
      if(i == 8)
        cout &lt;&lt; " ";
  
      if(i &gt;= 8)
      {
        byte2[i-8] = s;
        cout &lt;&lt; byte2[i];
      }
    }
  
    //Here I need to swap the two bytes
    return *x;
  }   
  </code></pre>
  
  <p>My code has two problems I am hoping you can help me solve.</p>
  
  <ol>
  <li>For some reason both of my bytes are 01000000</li>
  <li>I really am not sure how I would swap the bytes. My teachers notes on bit manipulation are very broken and hard to follow and do not make much sense me.</li>
  </ol>
  
  <p>Thank you very much in advance. I truly appreciate you helping me.</p>