Write a function that returns the value whose binary bit pattern is flipped from left to right.

topic:

Write the function:

unsigned int reverse_bit(unsigned int value);
This function returns the value after the binary bit pattern of value is reversed from left to right.

On a 32-bit machine the value 25 contains the following bits:

00000000000000000000000000011001
After flip: (2550136832)
10011000000000000000000000000000
Program result returned:
2550136832

analysis of idea:

  1. The bit length of unsigned int can be obtained by calculation, len=sizeof(unsigned int)*8; This can limit the number of loops,
  2. By looping and adding the given number with 1, the value of the lowest bit is obtained, which can be moved left to the highest bit, and the value is continuously moved to the right, thereby traversing each bit of the value.

code show as below:

#include<stdio.h>
#include<stdlib.h>
 unsigned int reverse_bit(unsigned int value)
{
    int ret=0;
    unsigned int len=sizeof(unsigned int)*8;//计算所给数占的二进制位
    int i;
    for(i=0;i<len;i++)
    {
        int r = value & 1;  //所给数与1相与得到它的最低位
        ret |=r<<(len-i-1);//最低位左移(len-i-1)位,到最高位,在和ret或
        value>>=1;     //所给数右移一位,去掉最低位
    }
    return ret;
 }
 int main()
 {
     unsigned int val;
     scanf("%u",&val);
     printf("%u\n",reverse_bit(val));  //%u以无符号十进制输出
     system("pause");
     return 0;
 }

operation result
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764778&siteId=291194637