Start with a number whose mantissa is your number (00000011
in your example) and whose exponent is 01111111
(127
, which is how 0 is stored in excess-of-127)
Count how many bits are from the LSb to the last set bit (not included). For each bit counted, add 1 to the exponent.
In your example: there are only one bit from the LSb to the last (most significant) bit set, so the exponent is added by 1 resulting in 128 (10000000
).
Shift left your mantissa (your original number) so the left-most set bit is lost. Take into account that the shift must be performed using a variable capable of holding at least 23 bits. So in your example, the original mantissa is 00000000000000000000011
. You must shift left it until the left-most '1' is lost, resulting in 10000000000000000000000
About the sign, if the original number is in 2-complement, simply take the MSb, and that will be your sign. In your example, 0 (positive)
So your result will be:
Sign : 0
Exponent: 10000000
Mantissa: 10000000000000000000000
Another example: convert the short int number -234
into a float.
-234
using 2-complement is stored as 1111111100010110
(16 bits)
From here it's easy to get the sign: 1 (the MSb)
We must work with the absolute magnitude, so we complement the number to get the positive (magnitude) version. We can do it by xoring it with 1111111111111111
, then adding 1. This gives us 0000000011101010
(234)
Initial mantissa (using 23 bits): 00000000000000011101010
Initial exponent: 01111111
(127)
Count how many bits are from the LSb to the left-most set bit, withouth including it. There are 7 bits. We add this to our exponent: 127+7=134 = 10000110
The mantissa is shifted left until the left-most set bit is gone. This gives us:
11010100000000000000000
Our number will be: 1 10000110 11010100000000000000000
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…