0

Why does this property hold true?

say the kth bit from right side is the first set bit in number 'x'. (x-1) will toggle every bit upto kth bit from right side.

I can verify this property by writing the bit sequence for the numbers but I don't understand as to why this property is true? Can anyone help me with a simple proof or intuition as to why this works?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Varun Hegde
  • 349
  • 2
  • 12

2 Answers2

2

It's the same reason if you do (x-1) where x is a base 10 integers all the zeros (if any) on the right will become nines.

9324930000000 - 1 = 9324929999999
Mathieu Pagé
  • 10,764
  • 13
  • 48
  • 71
1

Let's do a hand subtraction

  xxx100...00
- xxx000...01
─────────────
  xxx011...11

x represents bits that we don't care

Starting from the right, 10 - 1 = 1, borrowing 1 from the next column

Then the next one is 0 - 0, minus the borrow, which also results in 0 - 1 = 1 borrows 1. This sequence continues until the bit in subtrahend is 1, now we have 1 - 0 - borrow = 1 - 1 = 0

As the result, all the bits up to the rightmost set bit will be inverted

phuclv
  • 37,963
  • 15
  • 156
  • 475