W
W
WTFAYD2017-10-14 20:56:06
C++ / C#
WTFAYD, 2017-10-14 20:56:06

How is the conversion from a fixed-point number to a floating-point number done?

Problem: You need to convert a fixed point number to a floating point number. I found the code on the Internet, slightly altered it for myself and compiled:

int a = 0x001A8000; // Q16.16, число 26.5
float b = a/65536.0;

The code really works.
Can you please tell me why in this case the variable a is divided by 65536 (2 ^ 16, as I believe, is related to the number of digits for the integer and fractional parts)? How is this mathematically justified?
PS Found on wikipedia that X = X' * Z where X is a fixed point number (in my case b), X' is an integer representation (in my case a) and z - 2^-f is the weight of the least significant digit . But why is f equal to 16 in our case, and why exactly is 2^-f used?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2017-10-14
@15432

Specifically, in your example, this is what happens:
1) the variable "a" is assigned the value 1736704
2) the variable "a" is converted to float, the value is 1736704.0
3) the floating point numbers are divided - 1736704.0 by 65536.0
4) the result of division (26.5) is written to the variable "b"
The actual number conversion you're asking about only happens in step 2. On the x86 architecture, it's done using special assembler instructions and a floating-point coprocessor. That is, quickly and automatically. In simpler architectures, this can be implemented programmatically (just calculate the exponent and mantissa)
https://en.wikipedia.org/wiki/%D0%AD%D0%BA%D1%81%D...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question