c - floating point multiplication using bit manipulation -
this question has answer here:
i'm trying solve problem need return bit-level equivalent of unsigned floating point number times 4.
so far i've been exploring other answers , found 1 pretty similar mine, didn't work. there wasn't explanation given i'm trying understand getting wrong when run test cases.
when test problems
33554432[0x2000000].
but should
25165824[0x1800000]
so far code is
unsigned = (uf >> 0x17) & 0xff; unsigned b = uf & 0x80000000; unsigned c = uf & 0x007fffff; if (a == 0xff || (a == 0x0 && c == 0x0)) return uf; if (a) { <<= 0x2; } else if (c == 0x7fffff) { c >>= 0x2; <<= 0x2; } else { c <<= 0x2; } return (a<<0x17|b|c); any advice?
unless writing software floating-point emulator (in case need more can give you), should let compiler handle this:
#include <stdint.h> #include <assert.h> static_assert(sizeof(float) == sizeof(uint32_t)); uint32_t multiply_by_4_as_float(uint32_t n) { union { uint32_t u; float f; } conv; conv.u = n; conv.f *= 4; return conv.u; } (this use of unions has unspecified, not undefined, behavior in c1999 technical corrigienda applied, , in c2011. in c1989 undefined, , in c++ may still undefined.)
(if you're asking question because need little bit of floating-point math in program can't use hardware floating point unit concrete reason, check compiler's documentation - there may option can set makes use own software fp. keep in mind software floating point orders of magnitude slower hardware.)
Comments
Post a Comment