Write a program to count set bits in a number

number of bits in a number

The test also returns true if the high byte is 0x80, so there are occasional false positives, but the slower and more reliable version above may then be used on candidates for an overall increase in speed with correct output. Before Sean A. On March 4,Pat Wood pointed out that the ANSI C standard requires that the bitfield have the keyword "signed" to be signed; otherwise, the sign is undefined.

Kernighan and Dennis M. Its virtue is in taking less slightly memory by computing the constants on the fly. So if we have a bit word with only the high bit set, then it will only go once through the loop. Devised by Sean Anderson, August 20, So on a bit word with only the high set, it will go through 32 iterations.

Evan Felix pointed out a typo on April 4, Because XORing a value with itself results in a zero byte and nonzero otherwise, we can pass the result to haszero.

The variation that is tuned to evenly distributed input values was suggested by David A.

C program to count number of ones and zeros

Typically, the obvious approach is best, though. It would be faster by 2 operations to use the formula and the log base 2 method that uses a lookup table, but in some situations, lookup tables are not suitable, so the above code may be best. Next, the binary number 0x in hex is shifted to the right by the value represented in the lowest nibble of v. This solution is the simplest one and useful if 1's are sparse and among the least significant bits. If the original number was a power of 2, then the decrement will reduce it to one less, so that we round up to the same original value. This version is 4 operations. On December 31, Chris Pirazzi suggested I add the faster version, which requires two operations for constant bit-widths and three for variable widths. Unfortunately, this behavior is architecture-specific. Typo spotted and correction supplied by Mike Keith, January 3, If there are k bits, then we need the arrays S and B to be ceil lg k elements long, and we must compute the same number of expressions for c as S or B are long. Subsequently, it adds a number that will result in an overflow to the high bit of a byte if any of the low bits were initialy set. The following log base 2 methods are faster than this one. The second variation involves slightly more operations, but it may be faster on machines with high branch costs e. Print "counter".

Bruce Dawson tweaked what had been a bit version and made it suitable for 14 bits using the same number of operations on Feburary 1,

Rated 10/10 based on 8 review
Download
Brian Kernighan’s Algorithm to count set bits in an integer