bin2dec.py

Created by pascal-chauvin

Created on June 16, 2019

696 Bytes

Donne la représentation d’une série de bits (chaîne alphanumérique ou liste) en entier positif.


def str2dec(s):
  """ s est une chaine de caracteres """
  d = 0
  t = ""
  for x in s:
    if x in ['0', '1']:
      t += x
  k = len(t) - 1
  for x in t:
    d += int(x) * (2 ** k)
    k -= 1
  return d

def list2dec(l):
  """ l est une liste de 0 et de 1 """
  s = ""
  for x in l:
    if x in [0, 1]:
      s += str(x)
  return str2dec(s)

def decimal(d):
  """ representation en base 10 """
  if type(d) is str:
    return str2dec(d)
  else:
    return list2dec(d)

print(decimal("0001 1000"))

print(decimal([1, 0, 1, 1]))

print(decimal("1111 1111.1111 1111.1111 1111.1111 1111"))

x = str(input("nombre (par ex. \"0001 1000\" ou \"[1, 1, 0, 0, 0]\") ? "))
print(decimal(x))

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.