Search code examples
pythonpython-3.xbit-manipulation

Bit Manipulation Hacker's Delight in Python


I'm trying to get into the book "Hacker's Delight." The first formula in chapter 2 is x & (x -1) and is supposed to "turn off the rightmost 1-bit in a word producing 0 if none (e.g. 01011000 -> 0101000)." I have no idea why someone would want to do this.

I translated this into python as bin(0b1011000 and (0b1011000 - 1)) and got '0b1010111'. Is this correct?

I tried leaving out the "b" designating leading zeros and got this wild result '0b11110110110100110111'.

Am I close to correct?


Solution

  • Try these a few examples and see if you can tell the correctness yourself:

    >>>x = 15
    >>>bin(x)
    '0b1111'
    
    >>>x & (x -1)
    14
    >>>bin(14)
    '0b1110'
    
    # now try this x = 10
    >>>x = 10
    >>>bin(x)
    '0b1010'
    >>>x & (x - 1)
    8
    >>>bin(8)
    '0b1000`     # <---- see the rightmost bit is gone *rightmost 1*