Float to fixed, without an FPU

Michael Herf
April 5, 2000

I was talking to Matt Wronkiewicz, a colleague of Anton's, who's working on OpenGL for the Palm. The Palm has no FPU.

He is letting the user enter input as floating point, but converts them to fixed point, which he said was slow.

I did a quick implementation of float to fixed using no floating point instructions, and it's not particularly brilliant, but it shows how to mess with IEEE floating point.

Have a look at the code:

typedef unsigned long uint32;
typedef long int32;

// float to fixed using no FP ops or branches
inline int32 FloatToFixed(float *f)
{
 uint32 i     = *(uint32*)f;

 uint32 m     = (i & 0x7FFFFF) | (1 << 23);
 int32 expn   = (i >> 23 & 0xFF) - 134;
 uint32 sign  = (i >> 31);

 uint32 esign = -int32(uint32(expn) >> 31);
 uint32 lsh   =  expn & ~esign;
 uint32 rsh   = -expn &  esign;
 uint32 fixed = m << lsh >> rsh;

 return (fixed ^ (0 - sign)) + sign;
}