float2bin.py

Created by florian-allard

Created on August 14, 2020

1.23 KB

Convertisseur flottant vers binaire et inversement.


def float2bin(x):
  ent,frac=int(x//1),x%1
  ent_bin=bin(ent)
  frac_bin=''
  k=frac
  for i in range(16):
    k=k*2
    if k<1:
      frac_bin += '0'
    else:
      frac_bin += '1'
      k=k-1
  while frac_bin[-1]=='0':
    frac_bin=frac_bin[:-1]
  return (ent_bin,frac_bin)
  
def bin2float(ent_bin,frac_bin):
  ent=int(ent_bin)
  k=0
  for i in range(len(str(frac_bin))):
    k+=int(str(frac_bin)[i])*(2**(-(i+1)))
  return ent+k
  
print("Usage :")
print("Conversion flottant → binaire : ")
print("float2bin(x) avec x un nombre")
print("quelconque. Le résultat est")
print("donné sous la forme d'un couple")
print("'0b'partie entière, partie fractionnaire")
input("- EXE pour la suite -")
print("Conversion binaire → flottant : ")
print("bin2float(ent,frac) avec ent la")
print("partie entière en binaire sous")
print("la forme '0b'partie entière et")
print("frac la partie fractionnaire")
print("mise entre guillemets si elle")
print("commence par un 0.")
input("- EXE pour la suite -")
print("\nExemples : ")
print("float2bin(2.24) renvoie")
print(float2bin(2.24))
print('\nbin2float(0b111,"01010") renvoie')
print(bin2float(0b111,"01010"))
print('\nbin2float(0b111,01010) renvoie')
print(bin2float(0b111,01010),"qui est faux")

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.