Hello Jonathan,
Can you please explain your point of view ?.
Note that, with any of the 2 codes, what is printed in hex
(with the %08x formatter, after converting to integer), is the hex value
of
the representation in machine format of the floating-point number.
This is normally dependent on the machine representation of the
floating-point
number. Normally, in this case, it should be 32-bit IEEE754 format.
(Look for it on Wikipedia, eg.)
If you look at the number : 0x404FA4F1 :
a. The MSB bit is the sign. Here it is 0 : positive
b. bit 30 to 23 are the exponent Here it is 0x80 or 128
c. bit 22 to 0 are the mantissa. Here it is 0x4FA4F1
... To convert it by hand: ...
linux>
bc -l
ibase = 16 (sets input to hex)
mant = 0x4FA4F1
dec_point = 0x800000 (the decimal point - cfr Wikipedia page)
exp = 80
ibase = A (sets input back to decimal)
exp_bias = 127 (cfr Wikipedia page on IEEE754)
(mant + dec_point)/dec_point * e(l(2)*(exp-exp_bias))
... and there you have the other representation !.
Note :
(mant + dec_point) : in IEEE754 the most significant bit is omitted from
the mantissa.
it is assumed to be 1.
e(l(2) * x) : method to calculate 2 ** x in bc.
Cheers,
Henri.
On 2023-07-11 11:44, Jonathan Wakely wrote:
On Mon, 10 Jul 2023 at 19:23, <henri.cloetens@xxxxxxxxxx> wrote:
Hello Amit,
If you want to do this conversion in C, proceed as follows :
#include "stdio.h"
#include "stdlib.h"
int main()
{
float a = 3.2444422 ;
int *p = (int *)(&a) ;
fprintf(stderr,"%08x\n",*p) ;
}
It will print the hex value, which happens to be the same as yours on
my
machine.
That code has undefined behaviour.
This would be valid:
float a = 3.2444422 ;
int i;
memcpy(&i, &f, sizeof(int));
fprintf(stderr,"%08x\n",i) ;