Search code examples
javascriptbit-manipulationbitwise-operatorsbit-shift

Bitwise operation positive number to negative


Performance and optimisation debates aside.

I'm looking for a way in Javascript to take a number let it be 5 and using bitwise operations change it to -5.

The problem with flipping the bits is that 0 becomes 1 ergo ~5 becomes -6.

Is there a way to do this purely through bitwise ops? I feel that adding the 1 back on would negate the minor improvement that I may or may not gain.


Solution

  • The negative number as an integer is the two's complement. To flip the sign using two's complement you do like this:

    "To get the two's complement of a binary number, the bits are inverted, or "flipped", by using the bitwise NOT operation; the value of 1 is then added to the resulting value, ignoring the overflow which occurs when taking the two's complement of 0."

    In JavaScript that would be:

    n = ~n + 1;
    

    If you are looking for performance, that is not likely to be the fastest way. That would most likely be to use the operator specifically designed for that:

    n = -n;