Integer Byte Swapping in C++

It looks like you are trying to swap them a single bit at a time. That's a bit... crazy. What you need to do is isolate the 2 bytes and then just do some shifting. Let's break it down:

uint16_t x = 258;

uint16_t hi = (x & 0xff00); // isolate the upper byte with the AND operator

uint16_t lo = (x & 0xff); // isolate the lower byte with the AND operator

Now you just need to recombine them in the opposite order:

uint16_t y = (lo << 8); // shift the lower byte to the high position and assign it to y
y |= (hi >> 8);         // OR in the upper half, into the low position

Of course this can be done in less steps. For example:

uint16_t y = (lo << 8) | (hi >> 8);

Or to swap without using any temporary variables:

uint16_t y = ((x & 0xff) << 8) | ((x & 0xff00) >> 8);       

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;