Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
- C
- Clojure
- C++
- C#
- C#
- D
- Dart
- Fortran
- Go
- Go
- Haskell
- JS
- Java
- Java
- Lisp
- PHP
- Pascal
- Pascal
- Perl
- Perl
- Python
- Python
- Ruby
- Rust
uint32_t c = i;
c = (c & 0x55555555) + ((c & 0xAAAAAAAA) >> 1);
c = (c & 0x33333333) + ((c & 0xCCCCCCCC) >> 2);
c = (c & 0x0F0F0F0F) + ((c & 0xF0F0F0F0) >> 4);
c = (c & 0x00FF00FF) + ((c & 0xFF00FF00) >> 8);
c = (c & 0x0000FFFF) + ((c & 0xFFFF0000) >> 16);
add even and odd bits
then add even and odd pairs of bits
then add even and odd quadruples of bits
then add even and odd octets of bits
then add whatever groups of 16 bits are called
done
with gcc you can also use the function _builtin_popcount
then add even and odd pairs of bits
then add even and odd quadruples of bits
then add even and odd octets of bits
then add whatever groups of 16 bits are called
done
with gcc you can also use the function _builtin_popcount
uint32_t c = 0;
for (; i; i &= i - 1, ++c);
add even and odd bits
then add even and odd pairs of bits
then add even and odd quadruples of bits
then add even and odd octets of bits
then add whatever groups of 16 bits are called
done
with gcc you can also use the function _builtin_popcount
then add even and odd pairs of bits
then add even and odd quadruples of bits
then add even and odd octets of bits
then add whatever groups of 16 bits are called
done
with gcc you can also use the function _builtin_popcount
var c = i.toRadixString(2).replaceAll('0','').length;
c = popcnt(i)
func PopCountUInt64(i uint64) (c int) {
i -= (i >> 1) & 0x5555555555555555
i = (i>>2)&0x3333333333333333 + i&0x3333333333333333
i += i >> 4
i &= 0x0f0f0f0f0f0f0f0f
i *= 0x0101010101010101
return int(i >> 56)
}
func PopCountUInt32(i uint32) (n int) {
i -= (i >> 1) & 0x55555555
i = (i>>2)&0x33333333 + i&0x33333333
i += i >> 4
i &= 0x0f0f0f0f
i *= 0x01010101
return int(i >> 24)
}
This was useful only before go 1.9.
See math/bits.OnesCount instead.
See math/bits.OnesCount instead.
c = Data.Bits.popCount i
const c = i.toString(2).replace(/[^1]/g, '').length
• Convert the number to binary
• Replace characters that aren't '1' by turning them to ''
• See how long the resulting list of '1's is
• Replace characters that aren't '1' by turning them to ''
• See how long the resulting list of '1's is
int c = new BigInteger(valueOf(i), 2).bitCount();
(setf c (logcount i))
$i = base_convert($i,10,2);
$x = str_replace(0,'',$i);
$c = strlen($x);
function BitCount(N: Int64): Integer;
var
Q: QWord;
i: Integer;
begin
Result := 0;
Q := QWord(N);
for i := 0 to (8 * SizeOf(N) - 1) do
begin
if ((Q and 1) = 1) then Inc(Result);
Q := Q shr 1;
end;
end;
Not optimized at all.
c := PopCnt(i);
# Not best, but simple:
$c=0;
while ($i) {
$c += $i&1;
$i /= 2;
}
c = i.digits(2).count(1)