编写函数:
unsigned int reverse_bit(unsigned int value);
这个函数的返回值value的二进制位模式从左到右翻转后的值。
如:
在32位机器上25这个值包含下列各位:00000000000000000000000000011001
翻转后:(2550136832) 10011000000000000000000000000000
程序结果返回: 2550136832
程序1:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <math.h>
unsigned int reverse_bit(unsigned int value)
{
int sum = 0;
int i = 0;
int bit = 0;
for (i = 0; i<32; i++)
{
sum = sum << 1; //左移
bit = value & 1; //按位与
sum = sum | bit; //按位或
value = value >> 1; //右移
}
return sum;
}
int main()
{
printf("%u\n", reverse_bit(25));//1的翻转
system("pause");
return 0;
}
程序2:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <math.h>
unsigned int reverse_bit(unsigned int value)
{
double sum = 0;
int i = 0;
int bit = 0;
for (i = 1; i <= 32; i++)
{
bit = value & 1;
sum += bit * pow(2, 32 - i); //pow(i,j)表示i^j;
value = value >> 1;
}
return sum;
}
int main()
{
printf("%u\n", reverse_bit(25));//1的翻转
system("pause");
return 0;
}