Skip to content

Instantly share code, notes, and snippets.

@mike-pete
Last active May 1, 2020 21:11
Show Gist options
  • Save mike-pete/9a4cb2c6291f018bad045cd0115e8bfa to your computer and use it in GitHub Desktop.
Save mike-pete/9a4cb2c6291f018bad045cd0115e8bfa to your computer and use it in GitHub Desktop.
# 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