【本文链接】
http://www.cnblogs.com/hellogiser/p/swap-odd-even-bits.html
【分析】
假定一个数字是8位数,设为ABCDEFGH
ABCDEFGH &10101010 后右移一位得到0A0C0E0G
ABCDEFGH&01010101后左移一位得到B0D0F0H0
将上述两个结果0A0C0E0G和B0D0F0H0做或运算得到BADCFEHG
【代码】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/*
version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/9/18 */ /* (ABCDEFGH &10101010)>>1 ===>0A0C0E0G (ABCDEFGH&01010101)<<1 ===>B0D0F0H0 0A0C0E0G | B0D0F0H0 ===>BADCFEHG */ int SwapOddEvenBits(int x) { return ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1); } |