17.01.2013 Views

musicdsp.org source code archive - WSInf

musicdsp.org source code archive - WSInf

musicdsp.org source code archive - WSInf

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Double to Int (click this to go back to the index)<br />

Type : pointer cast (round to zero, or 'trunctate')<br />

References : Posted by many people, implementation by Andy M00cho<br />

Notes :<br />

-Platform independant, literally. You have IEEE FP numbers, this will work, as long as your not expecting a signed integer back larger than 16bits :)<br />

-Will only work correctly for FP numbers within the range of [-32768.0,32767.0]<br />

-The FPU must be in Double-Precision mode<br />

Code :<br />

typedef double lreal;<br />

typedef float real;<br />

typedef unsigned long uint32;<br />

typedef long int32;<br />

//2^36 * 1.5, (52-_shiftamt=36) uses limited precision to floor<br />

//16.16 fixed point representation<br />

const lreal _double2fixmagic = 68719476736.0*1.5;<br />

const int32 _shiftamt = 16;<br />

#if BigEndian_<br />

#define iexp_ 0<br />

#define iman_ 1<br />

#else<br />

#define iexp_ 1<br />

#define iman_ 0<br />

#endif //BigEndian_<br />

// Real2Int<br />

inline int32 Real2Int(lreal val)<br />

{<br />

val= val + _double2fixmagic;<br />

return ((int32*)&val)[iman_] >> _shiftamt;<br />

}<br />

// Real2Int<br />

inline int32 Real2Int(real val)<br />

{<br />

return Real2Int ((lreal)val);<br />

}<br />

For the x86 assembler freaks here's the assembler equivalent:<br />

__double2fixmagic dd 000000000h,042380000h<br />

fld AFloatingPoint Number<br />

fadd QWORD PTR __double2fixmagic<br />

fstp TEMP<br />

movsx eax,TEMP+2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!