Last active
May 1, 2020 21:11
-
-
Save mike-pete/9a4cb2c6291f018bad045cd0115e8bfa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this program converts a floating point number from binary to decimal | |
# sign mantissa * 2**(exponent) | |
sign = 0 | |
exponent = '10100' | |
mantissa = '0110101110' | |
# convert binary to decimal | |
def bin2dec(n): | |
sum, x = 0, 1 | |
for i in reversed(n): | |
if i == '1': | |
sum += x | |
x*=2 | |
return sum | |
# convert mantissa to dec | |
def mantissa2dec(m): | |
sum, x = 0, 1.0 | |
for i in m: | |
x /= 2 | |
if i == '1': | |
sum += x | |
return 1+sum | |
bias = 2**(len(exponent)-1)-1 # bias = [2**(number of bits in exponent - 1)] -1 | |
mantissa = mantissa2dec(mantissa) # mantissa converted to decimal | |
exponent = bin2dec(exponent) - bias # exponent - bias | |
number = mantissa * 2**exponent # mantissa * 2**(exponent) | |
if sign: number *= -1 # make the number negative depending on the sign | |
print(number) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment