x&(x-1) ... why only 2's complement system?

Discussion in 'C Programming' started by Lax, Apr 9, 2008.

  1. Lax

    Lax Guest

    Why is the "x&(x-1)" trick for removing the least significant set bit
    from an integer only valid on 2's complement systems?
     
    Lax, Apr 9, 2008
    #1
    1. Advertisements

  2. Orders of Rear Admiral Grace Hopper.


    Consider signed-magnitude and the number -2. 1 for the sign, a bunch
    of binary 0s, then binary 10 at the end. x-1 is -3, which is
    1 for the sign, a bunch of binary 0s, then binary 11 at the end.
    Bitwise and the two together and you get 1 for the sign, a bunch of
    binary 0s, then binary 10 at the end. Which is the representation of -2
    which is the number you started with, so the technique does not work
    for signed-magnitude.


    With this example in mind, you should easily be able to determine
    whether the technique works for 1's complement systems.
     
    Walter Roberson, Apr 9, 2008
    #2
    1. Advertisements

  3. Because on a 2's compliment system (let's assume 8-bit for simplicity's
    sake) x-1 is the same as x+(0b11111111) or x+0xFF. Let's say, for
    example's sake, that x is 0b00101000 or positive 40. In that case,

    0b00101000
    + 0b11111111
    = 0b00100111 = 39

    0b00101000
    & 0b00100111
    = 0b00100000 which is the correct answer.

    However, this obviously relies on -1 being represented as the 2's
    compliment of one (invert all bits and add one). If the system uses
    some other method, it will be different and the bitmask will not be
    equal to x-1. For instance, in a one's compliment system, x-1 is
    represented as x+0b11111110.
     
    Falcon Kirtaran, Apr 9, 2008
    #3
  4. Lax

    Lax Guest

    Thank you all (for suggesting and showing counterexamples).

    So is this a good implementation-independent way of doing it?

    (signed)( x & ( (unsigned)x-1 ) )
     
    Lax, Apr 9, 2008
    #4
  5. No, the right way is to make x unsigned to begin with, and
    to forget about testing bits in negative integers.
     
    Peter Nilsson, Apr 10, 2008
    #5
  6. Hmm. I stand corrected.
     
    Falcon Kirtaran, Apr 10, 2008
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.