|>

|> Hello, I just happened to run into this group which could hopefully answer a

|> question on real number conversion.

|>

|> I'd like to find a _very_ fast algorithm which converts floating point numbers

|> to fixed point using C/C++ at a binary level ( rather than strings ). The reason

|> for being very fast is that I will have _mega_bytes of data to convert.

|>

|> If anyone knows of any general pseudocode algorithms or even ideas, please

|> e-mail me ( or post here ) if you can...

|>

Just use an union of your floating-point data type and and unsigned. Initialize

the floating-point part of the union with your data to convert and do the

comversion as:

1/ get the exponent exp

2/ substract the bias from the exponent (x7f for float, x3ff for double)

3/ get the mantissa

3'/ if implicit bit, add it to the mantissa

4/ shift right the mantissa by (N - exp), where N is 23 for float, 52

for double

5/ add the sign

Following is a quick and dirty routine to convert from float to int, take it

just as an illustration of the above:

union thirty_two

{

float f;

unsigned long l;

};

long f2i (float x)

{

long mant;

int exp, sign;

union thirty_two fp32;

fp32.f = x;

/* get the sign */

sign = fp32.l & 0x80000000;

/* get the exponent */

exp = (fp32.l >> 23) & 0xff;

/* remove the bias */

exp -= 0x7f;

/* get the mantissa and make the implicit bit explicit */

mant = fp32.l & 0x7fffff | 0x800000;

/* convert the fixed point mantissa to an integer */

mant >>= 23 - exp;

/* fix the sign and return */

return (sign) ? -mant : mant;

}

There are many issues not addressed in this simple example:

- overflow/underflow

- rounding (the above routine truncates)

Patrice.

--

Patrice L. Roussel