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