Reputation: 287
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.
Upvotes: 0
Views: 4370
Reputation: 1309
In case anyone is wondering how you would go back and forth between a negative & positive number (n) without using the + or - signs ...
n = ~n
add = 1
while add:
diff = add^n
carry = (add&n)<<1
add = carry
n = diff
print(n)
Upvotes: 0
Reputation: 700382
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;
Upvotes: 4
Reputation: 510
It's not soo much faster. It does not make sense. When you need to negate the number noone can do it better than your CPU. http://jsperf.com/minus-vs-not
Upvotes: 0