简体   繁体   中英

Decimal floating point to fixed point conversion

I'm attempting to scale the value 1e-4 in fixed point format, but I'm having difficulties getting accurate results. I would be very grateful for any assistance. .

Matlab :

fprintf('%10.16f|%10d|\n',fi(1e-4,0,32),storedInteger(fi(1e-4,0,32)))

0.0001000000000033 | 3518437209|

and

I'm doing this in C fixed point notation.

uint32_t eps = 3518437209;

eps = (uint32_t)(eps / ((uint64_t)1 << 45));

In contrast to my anticipation of

0.0001000000000033

the value of eps is

0

Thank you!!

The simplest way to do this in C — which I concede may not meet your requirements — is with something like this:

#include <stdio.h>
#include <inttypes.h>

int main()
{
    double val = 1e-4;
    uint32_t ival = val * 35184372088832. + 0.5;
    printf("%u\n", ival);
}

That magic scaling factor 35184372088832. is simply 2 45 , and I'm adding 0.5 so that it rounds to the nearest fixed-point value. This is an obvious way to do it, and it works fine for "ordinary" values, but it probably doesn't work so well for extreme values, and I'm not even sure it has guaranteed behavior for input values greater than about 1.22e-4.

To convert the fixed-point value back to floating-point so you can print it out, just do the reverse:

double val2 = ival / 35184372088832.;
printf("%.16f\n", val2);

On my machine, this prints 0.0001000000000033 .

If you want to do any of this without using values or arithmetic involving type double , it can be done, but it's going to be a lot harder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM