Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer Byte Swapping in C++

I'm working on a homework assignment for my C++ class. The question I am working on reads as follows:

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 ).

Here is my code so far:

#include <iostream>

using namespace std;

unsigned short int ByteSwap(unsigned short int *x);

int main()
{
  unsigned short int x = 258;
  ByteSwap(&x);

  cout << endl << x << endl;

  system("pause");
  return 0;
}

and

unsigned short int ByteSwap(unsigned short int *x)
{
  long s;
  long byte1[8], byte2[8];

  for (int i = 0; i < 16; i++)
  {
    s = (*x >> i)%2;

    if(i < 8)
    {
      byte1[i] = s;
      cout << byte1[i];
    }
    if(i == 8)
      cout << " ";

    if(i >= 8)
    {
      byte2[i-8] = s;
      cout << byte2[i];
    }
  }

  //Here I need to swap the two bytes
  return *x;
}   

My code has two problems I am hoping you can help me solve.

  1. For some reason both of my bytes are 01000000
  2. 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.

Thank you very much in advance. I truly appreciate you helping me.

like image 262
Rob S. Avatar asked Oct 12 '10 15:10

Rob S.


1 Answers

I think you're overcomplicating it, if we assume a short consists of 2 bytes (16 bits), all you need to do is

  • extract the high byte hibyte = (x & 0xff00) >> 8;
  • extract the low byte lobyte = (x & 0xff);
  • combine them in the reverse order x = lobyte << 8 | hibyte;
like image 159
nos Avatar answered Oct 02 '22 11:10

nos