22 #define F32_SIGN BIT(31)
23 #define F32_EXP_SHIFT 23
24 #define F32_EXP_MASK ( MASK(8) << ( F32_EXP_SHIFT ) )
25 #define F32_EXP_BIAS 127
26 #define F32_FRAC_MASK MASK(23)
27 #define F32_FRAC_SIZE 23
29 static const int fltDecToMul[] = {
41 static int countbits(uint32_t val)
44 for (c = 0; val != 0; val >>= 1, c++) {};
48 static int32_t _fltToI32(
f32_t vin, uint32_t multiplier,
bool applySign)
53 int shift = ((vin & F32_EXP_MASK) >> F32_EXP_SHIFT) - F32_EXP_BIAS;
56 int32_t vout = vin & F32_FRAC_MASK;
59 vout |= 1 << F32_FRAC_SIZE;
62 shift -= F32_FRAC_SIZE;
65 if (multiplier > 0xFF)
67 int toomany = countbits(multiplier) - 8;
83 vout = (int32_t)((uint32_t)vout >> (-shift));
85 if (applySign && (vin & F32_SIGN)) vout = -vout;
92 return _fltToI32(vin, multiplier,
true);
99 return _fltToI32(value, fltDecToMul[decimals],
false) % fltDecToMul[decimals];
104 return _fltToI32(value, 1,
true);
114 float r = val * (1.0f/(32768 >> (15 - fBits)));
128 if (val == 0)
return 0;
130 if (val < 0) { ival = -val; sign =
true; }
131 else { ival = val; sign =
false; }
133 zeros =
clz(ival) - 16;
135 ival = (ival << (zeros + 8)) & 0x007fffff;
136 ival |= (142 - (zeros + fBits)) << 23;
137 if (sign) ival |= F32_SIGN;
int32_t fltInt(f32_t value)
Returns the integer part of the floating point value.
uint32_t fltFrac(f32_t value, int decimals)
Returns the fractional part of the floating point with the specified number of decimals.
Special library for primitive IEEE 754 floating point handling without dragging all float support alo...
int clz(uint32_t val)
Count the leading zero's.
uint32_t f32_t
32 bit representation for float.
f32_t fltFromI16(int16_t val, int fBits)
Takes an integer value and converts it to a float.
Various useful functions.
int32_t fltToI32(f32_t value, uint32_t multiplier)
This takes a f32_t IEEE 754 single precision floating point, and converts it to a multiplied integer...