gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Shifting and FIXED question

#7762 - aran - Tue Jun 24, 2003 9:32 am

In a function that implements rotation/zoom arithmethics I have seen
the following snippets:

FIXED zoom = 1<<8;
y = (y * zoom)>>8;
bg->DX = ((bg->x_scroll<<8) - y*SIN[angle] - x*COS[angle]);
bg->PA = (COS[angle]*zoom)>>8;

What exactly is a FIXED and why does it have to be a FIXED in the above function? Does it mean zoom is unmodifyable? However I would want to zoom faster and slower, is that possible, if yes how would I change my zoom variable?

Also, am I correct that 1<<8 means as 1 as dual shifted eight bits to the left? Why did the author then shift after each operation, either 8 bits left or right?
Thanks

#7801 - Cyberman - Wed Jun 25, 2003 1:08 am

A good guess might be that FIXED is a tyoedef.

<< is a single operator.. it is the LEFT SHIFT operator.
>> is the RIGHT SHIFT operator.

The shift operator moves bits in the direction left or right within the size of the variable or constant.

So
u16 D = 1 << 8;
would be 0x100 in value.

each position shifted left is the same as multiplying by 2
and each position shifted right is the same as dividing by 2.

Notice y = (y * zoom) >> 8;

The variables have to have a large enough size so as not to loose precision. However this is the same as

y = (y*zoom)/256;

Remember it's NOT shifting it each operatoring.. it's taking a value and shifting it each operation.

The only variable that it could be considered that way is y.. though if it's in a function y is a new variable each time that's multiplied by the zoom factor.

Cyb

#9879 - aeberbach - Thu Aug 21, 2003 12:22 am

FIXED is a typedef of a standard type used for fixed point arithmetic - floating point is really slow on systems that don't have the hardware to handle it (which is why you would use a lookup table for sin values, for instance), and fixed point is a way to use integers to do floating point without the slowdown but with some loss of precision. The left and right shifts manipulate the values around the imaginary fixed decimal point. There's a good explanation of how it is used for rotation on thepernproject.com, go to the GBA tutorials.