Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 579
Rihards Avatar asked Jul 16 '11 18:07

Rihards


3 Answers

You need to add one after taking the bitwise negation. This is a property of two's complement number system. It is not related to Actionscript (aside from the alleged performance difference).

So, (~(-450)+1) gives 450
and (~(450)+1) gives -450.

As noted in comments, this answer is written in response to the question, to fix a minor issue in the question asker's experiment. This answer is not an endorsement of this technique for general software development use.

like image 54
rwong Avatar answered Nov 12 '22 23:11

rwong


Use the rule that says

~(x) = (-x)-1
like image 21
Ray Toal Avatar answered Nov 13 '22 01:11

Ray Toal


If two-complement is being used (usually the case), negation is complement then add 1:

-x == ~x + 1

Whether it's faster depends on what optimisations the compiler performs. When in doubt, test.

like image 38
MRAB Avatar answered Nov 13 '22 00:11

MRAB