andy_tse
andy_tse

Reputation: 189

Convert IEEE 754-floating point back to decimal in C language?

Is there any code that allows me to convert 32-bit number in IEEE 754-floating point format back to decimal number? Preferably in C?


Sorry for my bad description.

Say I have 0x43ab9567 (this is in ieee754-floating point format), and I to convert to decimal.

0x43ab9567 (ieee754-floating point ) ->343.1672 (decimal)

Upvotes: 0

Views: 8705

Answers (2)

AntoineL
AntoineL

Reputation: 936

Please try this code:

union { uint32_t b; float f; } u;
u.b = 0x43ab9567;
printf("%g\n", u.f);

Upvotes: 1

Raymond Hettinger
Raymond Hettinger

Reputation: 226171

Its is unclear whether you're looking for a string representation, mathematical transformation, or a tool to extract the components of a float:

To get a string representation, coerce to a double and call ftoa()?

float f = 3.14159;

printf("%s\n", ftoa((double) f)));

To extract the parts of the representation, coerce to a double, and then use frexp().

To manipulate in mathematically, using bit-shifts and and-masks to extract the three components (sign, exponent offset by 127, and the mantissa):

raw = 0x43ab9567;                
sign = raw >> 31;                            // 0
mantissa = (raw & 0x7FFFFF) | 0x800000;      // 11244903
exp = ((raw >> 23) & 0xFF) - 127 - 23;       // -15
result = mantissa * pow(2.0, exp);           // 343.1672

Upvotes: 3

Related Questions