// test.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h" #include <iostream>
#include <stdio.h>
using namespace std; //方法一是将结果保存在了另一个变量中,从a中取依次取最低位,放入放入ret的低位然后右移ret
int reverse(int a)
{
int ret= ;
for(int i= ;i<;i++)
{
ret = ret<<;
ret = ret|(a&);
a = a>>;
}
return ret;
}
//方法二是交换a的低位和高位,首先取低位和高位,然后用异或判断高位和低位是否相同,如果相同
//则不变,如果不同则高位和低位分别取反(利用异或上1)
int reverse2(int a)
{
unsigned int lowbit = ;
unsigned int highbit = ;
unsigned int low = 0x00000001;
unsigned int high = 0x80000000; for(int i = ;i < ;i++)
{
lowbit = a & low;
lowbit = lowbit >> i; highbit = a & high;
highbit = highbit >> ( - i); if(highbit ^ lowbit) //说明高位和低位不同,否则高位和低位相同则不用交换
{
int or = ;
a = a ^ (or << i); //低位取反
a = a ^ (or << ( - i));//高位取反
} low = low << ;
high = high >> ;
}
return a;
} int main()
{
unsigned int a = 0x01020304;
printf("按位翻转后结果为:%d\n",reverse(a));
printf("按位翻转后结果为:%d\n",reverse2(a)); }