How do i convert a fixed point number into a float?

412 Views Asked by At

Using Unity. I need to used fixed point to network some data deterministically. How do I convert a fixed point back into a float so that I can apply it to the objects transform?

public class Fixed
{
    private int front;
    private int back;

    private const uint MAX_32 = 4294967295;
}

This is the class I have for the fixed point number.

3

There are 3 best solutions below

0
John McFarlane On

Don't overthink it. Just scale your real number by a constant amount (ideally a power of two or ten, depending on your needs) and store in an integer. To convert back, divide by the same amount. In your case, consider multiplying the floating-point value by 4294967296.0 and assigning to a long.

1
zhuang liu On

As @NineBerry said, you can use the type Decimal to represent fixed point numbers:

    decimal fixedPointNum = 123.456m; // a fixed point number
    float floatNum = Convert.ToSingle(fixedPointNum); 
    Console.WriteLine(floatNum);
0
abel gladstone On

The answer depends on the range. If you are trying to represent the decimal numbers from (-1, +1) you could divide the input by 0x7FFFFFFF.

If you have some other range (let us say -256.0, 255.0) you could divide the input by 0x007FFFFF

It all depends what ranges are you expecting in your inputs