Hey there!
I want to multiply/divide (shift) a float with variable containing a
power-of-two value: 2, 4, 8, 16, ....
Is there such a function in the C standard library or the glibc library
that does this?
If not has anybody written some clever high-performance "hack" like:
1. Cast float pointer to a 32-bit integer pointer.
2. Perform the a bitwise shift on the mantissa part.
3. Cast it back.
For one thing, this would be implementation dependent, and is more than
certainly OT.
For other thing, the algorithm you describe wouldn't work. IEEE
standarized format (which is the most widespread format AFAIK) uses an
implicit 1 in the mantisa, so shifting the bits in the mantisa will
only multiply/divide the decimal part of the number (when expressed in
binary scientific notation).
If you really want to hack your way through this, the easiest way to do
it is add/substract to the exponent part. Anyway, there are special
cases you should consider:
- An exponent of 0 and a mantisa all 0's means 0. You should leave the
number unaffected.
- An exponent of 0 and a mantisa different of 0 is a special format for
extremely small numbers. In this case there is no implicit one. You
should shift the mantisa in this case. However keep in mind that you
may overflow this special format when multiplying, if this is the case
you should convert to the regular format (shift the mantisa till the
first one goes out, and add to the exponent part).
- An exponent all 1's and a mantisa all 1's means infinit. This value
should not be altered by your operations.
- An exponent all 1's and a mantisa with at least one 0 in it means NaN
(Not a Number, the result you get when you try to divide by 0). This
value should also be left untouched.
(I'm not a 100% sure about the last two cases, I would have to read the
IEEE standard to check. Anyway I am a 100% an exponent of all ones is a
special case.)
As you can see it's much better to simply use * and / and let the FPU
do its job (or whatever FPU emulation software your C implementation
uses if there's no FPU available).
HTH