Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 bitwise shift 0?

I came across this in some AS 3.0 code:

(duration >> 0)

Where duration is a Number. I think I know what a bitwise right shift does, but what's the point of shifting 0 bits? This happens a few times in the code, I'd like to understand what it does.

like image 961
Sietse Avatar asked Jun 25 '09 10:06

Sietse


People also ask

What does & Bitwise operator do?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

What value does a Bitwise and operator return if 1 bit is true and one is false?

The bitwise AND operator produces an output of 1 if the corresponding bits of both the operands are 1. If not, the output is 0. Example 1: Bitwise AND operation of two one-bit operands.


1 Answers

There are a few reasons for this..

Firstly, multiplication and division is actually quicker in some circumstances when we use shift left, shift right...

i.e. the number 1 in binary is 00000001 Shift it left to become 00000010 and it's now 2 .. i.e 1 x 2

Shift it twice to multiply/divide by 4, 3 times for 8, 4 times for 16, etc...

It's not used overly frequently, but in cases like a physics engine port from C/C++, processing vast amounts of data, or some of the 3d engines, we'll see shifts as a remenant of the original code, or simply for speed.

(You might see it on some J2ME mobile java games too for example, where floating point units aren't available i.e. shift a value left 10 bits so the remaining 10 bits acts like a kind of decimal point.. then shift it back for the real value when drawing to screen position, at the cost of the overall possible size)

The other use as mentioned is for a quick Math.floor(); - but with a key differernce. I did some benchmarks a few months back working with Box2D and found it hundreds of times quicker - odd since I assume both conversions are handled natively.

When rounding negative numbers,
Math.floor(-7.6) = -8 and (-7.6 <<0 ) = -7

I.e. <<0 on a Number (float) will round in the direction of 0.

like image 133
hfs Avatar answered Sep 19 '22 17:09

hfs