Use union to swap bytes : Union « Data Type « C++






Use union to swap bytes

Use union to swap bytes

#include <iostream>
using namespace std;

union UnionSwapbytes {
  unsigned char c[2];
  unsigned i;
  UnionSwapbytes(unsigned x);
  void swp();
};

UnionSwapbytes::UnionSwapbytes(unsigned x)
{
  i = x;
}

void UnionSwapbytes::swp()
{
  unsigned char temp;

  temp = c[0];
  c[0] = c[1];
  c[1] = temp;
}

int main()
{
  UnionSwapbytes ob(1);

  ob.swp();
  cout << ob.i;

  return 0;
}

           
       








Related examples in the same category

1.Anonymous UnionsAnonymous Unions
2.Defining and using union WordByteDefining and using union WordByte