Skip to content

Instantly share code, notes, and snippets.

@OmidNejadabbasi
Created October 22, 2021 08:19
Show Gist options
  • Save OmidNejadabbasi/108a2678fcd4d6f8c94a9709eb85caa2 to your computer and use it in GitHub Desktop.
Save OmidNejadabbasi/108a2678fcd4d6f8c94a9709eb85caa2 to your computer and use it in GitHub Desktop.
This program converts decimal numbers to 32-bit floating number. Like for input -8.125 it wil give you 1 10000010 00000100000000000000000
num = input("Enter the decimal number: ").split('.')
isNegative = '0 '
if num[0][0]=='-':
isNegative = '1 '
num[0] = num[0][1:]
res = ''
def toBinary(n):
s = ''
while n > 0:
s = str(n % 2) + s
n =int(n / 2)
if len(s) == 0:
s = '0'
return s
decimalDigits = num[0]
fraction = num[1]
binDcimal = ''
binDcimal += toBinary(int(decimalDigits))
binDcimal += '.'
fraction = float('0.' + str(fraction))
for i in range(46):
fraction *= 2
binDcimal += str(int(fraction) % 10)
fraction = float('0.' + str(fraction).split('.')[1])
binDecSplited = binDcimal.split('.')
if len(binDecSplited[0])==1:
if binDecSplited[0] == '1':
res = isNegative +'01111111 ' + binDecSplited[1][:23]
else:
power = 0
count = 23
while count > 0 and binDecSplited[1][0] != '1':
count -= 1
power -= 1
binDecSplited[1] = binDecSplited[1][1:]
res = isNegative + "{0:08b} ".format(127 + power - 1) + binDecSplited[1][1:24]
else :
power = len(binDecSplited[0][1:])
count = 23
res = isNegative + "{0:08b} ".format(127 + power) + (binDecSplited[0][1:] + binDecSplited[1])[:23]
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment