# Fixed Point number 4 bytes or 8 bytes with different scale factors - library to convert numbers?

-3

I have to read fixed point numbers either 4 bytes or 8 bytes and the location of the decimal moves for each item (a known location)(scale number)

Is there a library where this is automated? C/C++ is the language of choice

For Example:

This is assuming a scale of 20

``````double toDoublePrecisionFixedPoint(short first,short second,short third,short forth)
{
double d = 0;

int top = (first << 0x10) | (second & 0x0000FFFF);
top/=8;
top >>= 8;
d+=top;

long long a = 0x0;
a = ((long long)second&0x07FF)<< 0x20;
long long t = 0x0;
t = (((long long)third) << 0x10) & 0xFFFF0000;
long long f = 0x0;
f = (((long long) forth)) & 0xFFFF;
long long bottom =  a | t | f;

long long maxflag= 0x80000000000;
double dlong = (double)bottom/(double)maxflag;
d += dlong;

return d;
}
``````

This is assuming a scale of 15:

``````  float toSinglePrecisionFixedPoint (short first, short second)
{
float f;

float dec = ((float)second) / ((float)0x10000);

f = (float)first;

if(f> 0 && dec >0)
f += dec;
else if(f >0 && dec <0)
f += (1 + dec);
else if(f < 0 && dec < 0)
f += dec;
else if(f < 0 && dec >0)
f -= (1 - dec);
else if(f == 0)
f += dec;

return f;
}

void floatToShorts(float f,short*ret)
{
ret = 0x00;
ret = 0x00;
ret = (short)f;
double decimal = 0;

//THIS IS REMOVING THE WHOLE NUMBER
modf(f , &decimal);
ret = (short)(decimal * 0x10000);
}

void doubleToShorts(double d,short*ret)
{
ret = 0x00;
ret = 0x00;
ret = 0x00;
ret = 0x00;

d*=0x80000000000;
long long l = (long long)d;

ret = ((short)((l & 0xFFFF000000000000) >> 48));
ret = ((short)((l & 0x0000FFFF00000000) >> 32));
ret = ((short)((l & 0x00000000FFFF0000) >> 16));
ret = ((short)((l & 0x000000000000FFFF)));
}
``````

This was going okay for me until my project now needs a variable scale location. That is fine - but I'm just curious if there is a better way to do this? There must be a full library

This is complicated quickly and I can easily fat finger something making my code not work - I am also sure I am not doing as much error checking as I should be - so curious if there is a library.

c++
c
bit-manipulation
fixed-point