Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Created January 16, 2013 14:27
Show Gist options
  • Save ryasmi/4547430 to your computer and use it in GitHub Desktop.
Save ryasmi/4547430 to your computer and use it in GitHub Desktop.
Converting decimal numbers into floating point binary (Excess 64 format).
import math
# This solution assumes valid input in terms of type and range.
# Main returns the sign, exponent and mantissa in "Excess 64" format.
def main():
value = float(input("Enter a number. "))
sign = "0"
if value < 0:
sign = "1"
value = abs(value)
exponent = math.floor(math.log(value, 2))
mantissa = (value / (2 ** exponent)) - 1
mantissa = getBinary(mantissa, 0.5, 8)
exponent = getBinary(exponent + 64, 2 ** 6, 7)
return sign + exponent + mantissa
def getBinary(value, bitValue, bits):
binary = ""
for i in range(bits):
if value >= bitValue:
binary += "1"
value -= bitValue
else :
binary += "0"
bitValue /= 2
return binary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment