conversion_binaire.py

Created by vieirajerome31

Created on November 21, 2024

1.23 KB


from math import *

# Initialisation des variables globales
resultat_binaire = 0


# Conversion d'un nombre binaire en décimal
def conversion_binaire_to_decimal(): 
    global resultat_binaire
    binaire_nombre = input("Nombre binaire : ")
    for index, chiffre in enumerate(reversed(binaire_nombre)):
        if chiffre == '1':
            resultat_binaire += 2**index

# Conversion d'un nombre décimal en binaire
def conversion_decimal_to_binaire():
    global resultat_décimal
    decimal_nombre = int(input("Nombre décimal : "))
    binaire = ""

    # Cas où le nombre est 0
    if decimal_nombre == 0:
        binaire = "0"
    else:
        while decimal_nombre > 0:
            reste = decimal_nombre % 2  # Récupère le reste de la division par 2
            binaire = str(reste) + binaire  # Ajoute le bit à la chaîne
            decimal_nombre //= 2  # Divise par 2

    print("Le nombre binaire est : ", binaire)


# Sélection de la conversion
choix = 0
choix = input("1 = binaire vers decimale 2 = decimal vers binaire Choix = ")
if int(choix) == 1:
    conversion_binaire_to_decimal()
    print("Résultat binaire en décimal = ", resultat_binaire)
elif int(choix) == 2 :
    conversion_decimal_to_binaire()

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.