關於把一個無符號數的二進位制位翻轉的兩種實現方法
阿新 • • 發佈:2019-01-01
#include <stdlib.h> #include <stdio.h> #include <math.h> unsigned int reserve_bit(unsigned int num)//採用移位的方法使一個數的二進位制位翻轉後返回 { unsigned int ret = 0; int bit = 0; int i = 0; for (i = 0; i < 32; i++) { ret <<= 1; bit = num & 1; ret = bit | ret; num = num / 2; } //1000 0000 0000 0000 0000 0000 0000 0000 return ret; } unsigned int reserve1_bit(unsigned int num)//計算的方法 { int bit=0; unsigned int ret = 0; int i = 0; for (; i < 32; i++) { bit = num & 1; ret += bit*pow(2, 31 - i); num /= 2; } return ret; } int main() { unsigned int num = 0; unsigned int ret = 0; unsigned int ret1 = 0; scanf_s("%d", &num); ret = reserve_bit(num); ret1 = reserve1_bit(num); printf("ret = %u\n", ret); printf("ret1 = %u\n", ret1); system("pause"); return 0; }