您的位置:首页 > 其它

交换一个无符号整形数的奇偶位

2012-09-24 21:14 183 查看
void OddEventBitSwap1(unsigned &A)
{
unsigned int mask = 0x3;
int loop = sizeof(unsigned)*8/2;

for(int idx = 0; idx < loop; idx++)
{
if (((A & mask) != mask) && ((A & mask) != 0))
{
A = A^mask;
}
mask = mask << 2;
}
}

void BitSwap(unsigned &A, int pos1, int pos2)
{
unsigned p1Value = ((0x1<<pos1)&A)>>pos1;
unsigned p2Value = ((0x1<<pos2)&A)>>pos2;

A = A & (~((0x1<<pos1 | 0x1<<pos2)));

A = A | (p1Value<<pos2);
A = A | (p2Value<<pos1);
}

void OddEventBitSwap2(unsigned int &A)
{
int loop = sizeof(unsigned)*8/2;
int even = 0;
int odd = 1;
for (int idx = 0; idx < loop; idx++)
{
BitSwap(A, odd, even);
odd += 2;
even += 2;
}
}

void OddEventBitSwap3(unsigned int &A)
{
unsigned int oddValue  = A & 0X55555555;
unsigned int evenValue = A & 0XAAAAAAAA;

A = (oddValue<<1 | evenValue>>1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐