1

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?

Ryan
  • 1,312
  • 3
  • 20
  • 40
  • `and` is not the same as `&`. – kaya3 Oct 17 '22 at 01:04
  • Generally, yes, absolutely, but Python doesn't recognize &&, and I see no reason to switch languages to demonstrate that point. This is for fun, I'm not a student, so why switch to C? @kaya3 – Ryan Oct 17 '22 at 01:07
  • `&&` is also not the same as `&`. You need to write `&` for a bitwise "and" operation; this is true in Python, not just in C. – kaya3 Oct 17 '22 at 01:07
  • @kaya3 point well taken. – Ryan Oct 17 '22 at 01:24

1 Answers1

1

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*
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
  • 1
    Got it. I'm trying to get a deeper understanding of what's going on "under the hood" and the first two questions stopped me cold. Thank you! – Ryan Oct 17 '22 at 00:58
  • The interesting question from the OP remains: why would someone want to do this? – Tom Jun 29 '23 at 06:49