Can I turn negative number to positive with bitwise operations in Actionscript 3?

Viewed 26368

Is there a direct way how to turn a negative number to positive using bitwise operations in Actionscript 3? I just think I've read somewhere that it is possible and faster than using Math.abs() or multiplying by -1. Or am I wrong and it was a dream after day long learning about bytes and bitwise operations?

What I saw was that bitwise NOT almost does the trick:

// outputs: 449
trace( ~(-450) );

If anyone find this question and is interested - in 5 million iterations ~(x) + 1 is 50% faster than Math.abs(x).

6 Answers

Basically numbers 2' complement is the number in opposite sign.

if (num < 0) {
   PosNum = ~num + 1;
}
else {
   NegNum = ~num + 1;
}
Related