Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).
书上的方法很巧,分别将奇偶位提取,然后偶位右移一位,奇位左移一位,再或以下就行。
#include <iostream>
using namespace std;
int swap_bits(int x){
//a=1010 5=0101
return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) );
}
int main()
{
int x=6;
cout << swap_bits(x) << endl;//9 0110->1001
return 0;
}