Programma Python per convertire numeri decimali in binari
Dato un numero decimale come input, il compito è scrivere un programma Python per convertire il numero decimale fornito in un numero binario equivalente.
Esempi:
Input : 7 Output :111 Input :10 Output :1010
Metodo n. 1: Soluzione ricorsiva
DecimalToBinary(num): if num>= 1: DecimalToBinary(num // 2) print num % 2
Di seguito è riportata l'implementazione della soluzione ricorsiva di cui sopra:
Python3
# Function to convert decimal number> # to binary using recursion> def> DecimalToBinary(num):> > > if> num>> => 1> :> > DecimalToBinary(num> /> /> 2> )> > print> (num> %> 2> , end> => '')> # Driver Code> if> __name__> => => '__main__'> :> > > # decimal value> > dec_val> => 24> > > # Calling function> > DecimalToBinary(dec_val)> |
Produzione
011000
Metodo n. 2: Da decimale a binario utilizzando la funzione integrata
Python3
# Python program to convert decimal to binary> > # Function to convert Decimal number> # to Binary number> def> decimalToBinary(n):> > return> bin> (n).replace(> '0b'> , '')> > # Driver code> if> __name__> => => '__main__'> :> > print> (decimalToBinary(> 8> ))> > print> (decimalToBinary(> 18> ))> > print> (decimalToBinary(> 7> ))> |
Produzione
1000 10010 111
Metodo n. 3: Senza funzione integrata
Python3
# Python program to convert decimal to binary> > # Function to convert Decimal number> # to Binary number> def> decimalToBinary(n):> > return> '{0:b}'> .> format> (> int> (n))> > # Driver code> if> __name__> => => '__main__'> :> > print> (decimalToBinary(> 8> ))> > print> (decimalToBinary(> 18> ))> > print> (decimalToBinary(> 7> ))> |
Produzione
1000 10010 111
Metodo Ninja veloce: Codice a una riga per convertire il decimale in binario con l'input dell'utente
Python3
# Quick Ninja One line Code> print> (> bin> (> 4785> )[> 2> :])> |
Produzione
1001010110001
O
Python3
# Use this for user input> #decNum = int(input('Enter any Decimal Number: '))> decNum> => 4785> print> (> bin> (decNum)[> 2> :])> decNum1> => 10> print> (> bin> (decNum1)[> 2> :])> decNum2> => 345> print> (> bin> (decNum2)[> 2> :])> |
Produzione
1001010110001 1010 101011001
Utilizzando l'operatore di spostamento bit per bit>>.
Python3
def> dec2bin(number:> int> ):> > ans> => ''> > if> ( number> => => 0> ):> > return> 0> > while> ( number ):> > ans> +> => str> (number&> 1> )> > number> => number>>> 1> > > ans> => ans[::> -> 1> ]> > return> ans> def> main():> > number> => 60> > print> (f> 'The binary of the number {number} is {dec2bin(number)}'> )> # driver code> if> __name__> => => '__main__'> :> > main()> |
Produzione
The binary of the number 60 is 111100
Utilizzando il metodo di formattazione integrato:
Un altro approccio che utilizza la funzione format() incorporata. Questo approccio prevede la conversione del numero decimale in un numero intero e quindi l'utilizzo della funzione format() con l'identificatore di formato 'b' per convertirlo in una stringa binaria. La stringa binaria può quindi essere stampata o archiviata per un utilizzo successivo.
Ecco un esempio di come può essere utilizzato questo approccio:
Pitone
def> decimal_to_binary(decimal_num):> > binary_str> => format> (> int> (decimal_num),> 'b'> )> > return> binary_str> print> (decimal_to_binary(> 7> ))> # prints 111> print> (decimal_to_binary(> 10> ))> # prints 1010> #This code is contributed by Edula Vinay Kumar Reddy> |
Produzione
111 1010