Created
March 30, 2013 14:12
-
-
Save ThunderXu/5276835 to your computer and use it in GitHub Desktop.
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, and so on).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <bitset> | |
#include <string> | |
std::bitset<32> Swap(std::bitset<32>); | |
int main() | |
{ | |
int num; | |
std::cin>>num; | |
std::bitset<32> test(num); | |
std::cout<<Swap(test)<<std::endl; | |
} | |
std::bitset<32> Swap(std::bitset<32> input) | |
{ | |
using namespace std; | |
string str01 = "01010101010101010101010101010101"; | |
string str10 = "10101010101010101010101010101010"; | |
bitset<32> bt01(str01); | |
bitset<32> bt10(str10); | |
bitset<32> btEven = (input&bt10)>>1; | |
bitset<32> btOdd = (input&bt01)<<1; | |
return btEven|btOdd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment