# Swap Every Two Bits

From Software Engineers Wiki

Swap every two bits in an unsigned char. Swap bits at 0 and 1st position, swap 2nd and 3rd position, and so on.

## Answer

For 8 bit integer:

unsigned char swap_every_two_bits(unsigned char n) { return ((n & 0x55) << 1) | ((n & 0xaa) >> 1); }

For 32 bit integer:

unsigned char swap_every_two_bits(uint32_t n) { return ((n & 0x55555555) << 1) | ((n & 0xaaaaaaaa) >> 1); }