Fun with bits

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Fun with bits

Nicolas Cellier
Some beautiful things I just rediscovered:

Isolating the low bit of an integer x
   (x bitAnd: 0 - x)
Thus x lowBit is also:
   (x bitAnd: 0 - x) highBit
I dont' think I saw above implementation anywhere...

Otherwise, tricks below are known for long, but it's sometimes usefull
to refresh memory...

Removing the lowest bit of an integer x
    (x bitAnd: x - 1)
This explains isPowerOfTwo:
    x > 0 and: [(x bitAnd: x - 1) = 0]
Counting the bits in a positive integer is just as simple as:
    nBits := 0.
    [x = 0] whileFalse: [
        nBits := nBits + 1.
        x := x bitAnd: x - 1].
Enumerating the bits in a positive integer:
    [x = 0] whileFalse: [
        aBlock value: x lowBit.
        x := x bitAnd: x - 1].

Nicolas