This afternoon I was driving back from a meeting and thought I should put some code together to demonstrate the operations. Here it is (you will notice that I have used a somewhat more useful word length than 8 bits for this piece of code) :
#include <stdio.h>
double QFormatIntegerToFloat (const int x,
const int n)
{
return (((double)x) / ((double)(1 << n)));
}
int FloatToQFormatInteger (const double x,
const int m,
const int n)
{
int i;
int y;
int mask = 0;
y = (int)(x * ((double)(1 << n))); // Generate the integer number in m.n format
for (i = 0; i < (m+n); i++) // Calculate the mask to ensure we return the correct number of valid bits
{
mask = (mask << 1) + 1;
}
return (y & mask);
}
int MpyQFormatInteger (const int x,
const int y,
const int n)
{
long long tmp;
tmp = ((long long)x * (long long)y) >> n;
return ((int)tmp);
}
int main()
{
int a, b, c, d, e;
printf ("%lf = 0x%x\n", 2.0 , FloatToQFormatInteger (2.0 , 8, 24));
printf ("%lf = 0x%x\n", 1.5 , FloatToQFormatInteger (1.5 , 8, 24));
printf ("%lf = 0x%x\n", 0.5 , FloatToQFormatInteger (0.5 , 8, 24));
printf ("%lf = 0x%x\n", 0.25, FloatToQFormatInteger (0.25, 8, 24));
printf ("%lf = 0x%x\n", 0.75, FloatToQFormatInteger (0.75, 8, 24));
printf ("\n");
a = FloatToQFormatInteger (0.75, 8, 24);
b = FloatToQFormatInteger (2.0 , 8, 24);
c = MpyQFormatInteger (a, b, 24);
printf ("Result = 0x%x : %lf\n", c, QFormatIntegerToFloat (c , 24));
d = FloatToQFormatInteger (0.5 , 8, 24);
e = MpyQFormatInteger (c, d, 24);
printf ("Result = 0x%x : %lf\n", e, QFormatIntegerToFloat (e , 24));
return (0);
}
Here is the output :
2.000000 = 0x2000000
1.500000 = 0x1800000
0.500000 = 0x800000
0.250000 = 0x400000
0.750000 = 0xc00000
Result = 0x1800000 : 1.500000
Result = 0xc00000 : 0.750000
If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.
Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/
Copyright © 2015 Delta Numerix
No comments:
Post a Comment