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
3 Antworten
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")
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?
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")