I know there are number ways to read every bit of a IEEE 754 float using written libraries.
I don't want that, and I want to be able to manually convert a decimal float to binary representation based on IEEE 754.
I understand how IEEE 754 works and I am just trying to apply it.
I ask this question here just want to see whether my way is normal or stupid and I am also wondering how PC does it quickly.
If I am given a decimal float in a string, I need to figure out what the E is and what the M is.
get the two parts out: integer part
i
and fraction partf
.deal with
f
. I constantlymultiple 2
and get the integer part (either 0 or 1) and remove the integer part and then repeat, until it becomes 0convert
i
to bits. This is easy I just constantlymod 2
anddiv 2
to get all bits ofi
.
for example, to convert f
part
0.390625 * 2 = 0.78125 0
0.78125 * 2 = 1.5625 1
0.5625 * 2 = 1.125 1
0.125 * 2 = 0.25 0
0.25 * 2 = 0.5 0
0.5 * 2 = 1 1
0
In this case, the temparay bits of 0.390625
is 0 1 1 0 0 1
.
Now, I have the bits for i
and for f
.
If all bits for i
is 0, then on bits of f
I shift_left it until the first 1
is gone, according to the default hidden 1
of M
. I get M
, then give the value of shifting to E, considering of E
's baseline of course.
If i
is not 0, then I concatenate both bits part and calculate how many shift_right I need to do to make the concatenated bits to be 1, then give this value to E
I guess all my steps are not wrong. But I feel it very troublesome.
Is there a easy and clean way?
How does PC does it?