Updated 2015-07-09 00:08:28 by chiligrower

See Also  edit

Bit Manipulations
Iterate over an IP address Range, by kbk
Sierpiński triangle
A simple bit manipulation plays a role in a clever solution to a particular problem.

1-Bits in a positive int  edit

count the number of bits of value 1 in an integer

(sign-extended for negatives, so better use positives only):
proc nbits n {
    set f [format %X $n]
    set res 0
    foreach nybble {0 1 2 3 4 5 6 7 8 9 A B C D E F} \
        bits   {0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4} {
        set res [expr $res+$bits*[regsub -all $nybble $f - -]]
    }
    set res
} ;# RS

More than 30 times faster, and works for negative numbers too:
proc popcount { i } { # count the population of ones in the integer i
    set pop 0
    while { $i != 0 } {
        incr pop
        set i [expr { $i & ( $i - 1 ) }]
    }
    return $pop
} ;# kbk [http://titania.crd.ge.com/people/kennykb.html]

This one is slower than the last, but it's a one-liner:
proc nbits2 n {
    expr 0[string map {0 +0 1 +1 2 +1 3 +2 4 +1 5 +2 6 +2 7 +3 8 +1 9 +2 A +2 B +3 C +2 D +3 E +3 F +4} [format %X $n]]
}

For me, popcount freezes with negative numbers and popcount seems to be wrong for larger

numbers ( like 12345678901234567890 ). Here's my one-liner, only slightly slower than popcount

and shorter than nbits2. (chiligrower 20150708)
proc bcnt n { string length [ string map {0 ""} [ format %b $n ] ] }