下面的代码写的太罗嗦,请看我整理后的 对一个整数按位反转
void Fan1()
{
unsigned int Number;
unsigned int Temp1,Temp2,Temp3;
int i = 31;
Temp1 = 0xaaaaaaaa;
Temp2 = 1;
Temp3 = 0;
Number = 0;
printf("Number = 0x%x\n",Temp1);
for(i=31;i > 0; i-=2)
{
Number = Number | ( (Temp1 & Temp2) << i );
Temp2 = Temp2 <<1;
}
Temp2 = 0x80000000;
for(i=31;i > 0; i-=2)
{
Number = Number | ( (Temp1 & Temp2) >> i );
Temp2 = Temp2 >>1;
}
printf("Number = 0x%x\n",Number);
}
void Fan2()
{
unsigned int Number;
unsigned int Temp1,Temp2,count;
int i;
Number = 0xAAAAAAAA;
Temp1 = 1;
Temp2 = 0;
count = 1;
//printf("Number = 0x%x\n",Number);
for(i = 0;i < 16; i++)
{
count = 1;
//分别取高位和低位
Temp1 = Number & (count << i);
Temp2 = Number & (count << (31 -i));
//把高位和低位分别置零
Number = Number & (~(count << i));
Number = Number & (~(count << (31-i)));
//把取得的值移动相应的位
Temp1 = Temp1 << (31-2*i);
Temp2 = Temp2 >> (31-2*i);
//用或操作来对高位和低位赋值交换。
Number = Number | Temp1;
Number = Number | Temp2;
}
printf("Number = 0x%x\n",Number);
}
第一种方法是采用取一位放一位,第一个循环搞定“低16位->高16位”,第二个循环搞定“高16位->低16位”。
第二种方法是采用每次取两位来进行对换,共一个循环,16次可以对完。
阅读(1726) | 评论(0) | 转发(0) |