32 Analyzing a C language data, how many bits are 1, then sends out serial port

     Today, I encountered a problem, encountered a 32-bit data, write a subroutine to determine how much it is 1 bit. My idea is to start this becomes an array of 32-bit data capacity and to compare each bit is not 1, if it is 1, use another variable plus 1. Finally, return to this variable.

But this is not necessary and if not turn into an array do.

    

int count_bit (unsigned int a)  
{
int counts=0;    
    while (a)  {
      counts += a & 0x1u ;
      a >>= 1 ;
    }
return counts ;
}

      This subroutine, the 32-bit data you want to pass judgment come. Then on the first count value assigned 0. Then a determination is performed while loop cycle, if the data is not 0 into the while loop count value will return 0. After entering the while loop, the far right will be a data of an AND operation, if it is 1 plus 1 will cause the counts.

The data is then shifted to the right one for a determination of the next digit. Until judged complete 32-bit data. It will exit the loop.

     Then I defined a 32-bit data to verify the functionality of this function.

#include<inttypes.h >
int count_bit (unsigned int a)  
{
int counts=0;    
    while (a)  {
      counts += a & 0x1u ;
      a >>= 1 ;
    }
return counts ;
}
void setup() {
   Serial.begin(9600);  
}
uint32_t y=12341234;
int b =count_bit(y);
void loop() {
   Serial.print(b);
   delay(1000); 
}

This 32-bit data is judged that there is a 10 bits.

Guess you like

Origin www.cnblogs.com/dzswise/p/11278818.html