The following code computes unsignedint x
The number of bytes in this number is 1,
int bit_count(unsigned int x ) { static unsigned int mask[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF }; int i; int shift; /* number of positions to shift to right */ for( i=0, shift=1; i < 5; i++, shift *= 2 ) x = (x & mask[i]) + ( (x >> shift) & mask[i] ); return x; }
So what about understanding this question? Why does it calculate an unsigned
What is the number of 1 bytes in Int?
After checking the information, I finally learned that this is a counter merging problem.
It adds 0-bit and 1-bit data. The final total number is equal to the number of 1 digits in the data.
Where mask [0] = 0x55555555 = 01010101 01010101 01010101 01010101 (01 interval)
Mask [1] = 0x33333333 = 00110011 00110011 00110011 00110011 (01 interval 2 bits)
Mask [2] = 0x0f0f0f = 00001111 00001111 00001111 00001111 (01 4-digit interval)
Mask [3] = 0x00ff00ff = 00000000 11111111 00000000 11111111 (01 8-bit interval)
B [4] = 0x0000ffff = 00000000 00000000 11111111
(01 interval: 16 digits)
The 32-bit (unsigned INT) of the input number is considered as 32 counters, representing the number of 1 in each bit. Then combine two adjacent "counters" to convert I into 16 counters. The value of each counter is the number of the two bits; merge two adjacent "counters" to convert I into eight counters. The value of each counter is the number of one of four bits .. And so on until I is converted into a counter, then its value is the number of BITs whose I value is 1 in 32bit.
For example, a piece of data is 10110011 (Binary), and the binary value of the hexadecimal constant 0x55 is 01010101 (the valid data is only 8 bits, and the preceding value is 0, not considered ). In the first operand of this addition, Data performs the and operation with this constant, and the odd bit is taken out. Second operand (data>
1) & 0x55), first move all the even digits to odd digits, and then use the same mask to get these identical digits. Now, the first operand contains an odd number of data, and the second operand contains an even number. Adding these two operands is equivalent to adding the odd and even bits of data. The bit of this byte is divided into four two bits to demonstrate that four independent additions are actually executed. Of course, the total number of digits has not been calculated yet. However, you can use the same technology as above to calculate the total number. Finally, a number is the number of 1 bytes.
In this way, we can calculate the number of 1.