Can I turn a negative number into a positive with bitwise operations in ActionScript 3?

Is there a direct way to turn a negative number into a positive using bitwise operations in ActionScript 3? I just think I read somewhere that this is possible and faster than using Math.abs()or multiplying by -1. Or am I mistaken, and it was a dream after a day's study of bytes and bitwise operations?

What I saw was that bitwise NOTalmost does the trick:

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

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

+7
source share
6 answers

. . ActionScript ( ).

, (~(-450)+1) 450
(~(450)+1) -450.

, , . .

+14

,

~(x) = (-x)-1
+9

( ), , 1:

-x == ~x + 1

, . , .

+4

- , -. , .

negativeX = -positiveX; // is the same as (~positiveX) + 1

.

, , , ?: , Math.abs().

positiveX = unknownX < 0 ? -unknownX : unknownX;
+1

2 ' .

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

:

var number:Number = 10;
//Makes a number
trace(number)
//Tells you the number BEFORE converting
number = number - number * 2;
//Converts number
// Takes number times 2 and subtracts it from original number
trace(number);
//Tells you the number AFTER converting

, , , :

var number:Number = 10;
number = number - number * 2;
-2

All Articles