0

create a function that implements an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents and for invalid input, return string Invalid input.

Algorithms

7th Sep 2016, 2:34 PM
brian
3 Réponses
0
src = int(input("enter int from [0,255]: ")) if (src>=0 and src<=255): shift = 128 bin_src="" while shift >0: if (src & shift): bin_src += '1' elif bin_src != "" or shift == 1: bin_src += '0' shift >>= 1 print("binary representation for {0} is {1}".format(src,bin_src)) else: print("invalid input")
8th Sep 2016, 4:48 AM
Textobot
Textobot - avatar
0
Thank you textobot, but I keep running errors when I run the code, also I don't kniw what the bin_src means, is there a way of simplifying the code-if possible?
9th Sep 2016, 5:42 PM
brian
0
Which input exactly causes errors? bin_src is binary representation of number in string format. I don't know how to really simplify this code - if we want to get representation of src as sum of degrees of 2, using shift operators is the shortest way I know. We may get rid of 'elif' and start from lower bits, but we will need to revert resulting string in the end. src = int(input("enter int from [0,255]: ")) if (src>=0 and src<=255): shift = 1 bin_src="" while shift <= src: if (src & shift): bin_src += '1' else: bin_src += '0' shift <<= 1 print("binary representation for {0} is {1}".format(src, bin_src[::-1])) else: print("invalid input")
13th Sep 2016, 9:55 AM
Textobot
Textobot - avatar