//Given an unsigned 8 - bit integer, swap its even and odd bits.The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on.
//For example, 10101010 should be 01010101. 11100010 should be 11010001.
//Bonus: Can you do this in one line ?
// This is really only challenging if you go for the one-liner, I did not have time to do so ;(
#include <iostream>
using namespace std;
unsigned swapBits(unsigned number)
{
bool even, odd;
for (unsigned i = 0; i < 8; i++)
cout << ((number >> i) & 1U) << " ";
cout << endl;
// Loop through all 8 bits, 2 at a time
for (unsigned n = 0; n < 8; n+=2)
{
even = (number >> n) & 1U; // get the even bit
odd = (number >> n+1) & 1U; // get the odd bit
number ^= (-even ^ number) & (1UL << n+1); // set the n+1 bit to the n'th bit value
number ^= (-odd ^ number) & (1UL << n); // set the n'th bit to the n+1 bit value
}
for (unsigned i = 0; i < 8; i++)
cout << ((number >> i) & 1U) << " ";
cout << endl;
return number;
}
int main(int argc, char** argv)
{
unsigned result = swapBits(157);
cout << "Result: " << result << endl;
return 0;
}
Comments