0
Decimal to binary conversion in python
Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents. For any invalid input, return string Invalid input Example: For number 5 return string 101 MY CODE: binary=0 def binary_converter(data): global binary if data ==0: return"invalid conversion" elif data < 0: return"input below 0 not allowed" elif data > 255: return"input above 255 not allowed" else: remainder= data%2 data/=2 binary=binary+(remainder*1) return binary can someone tell me whats wrong with my code
3 Antworten
+ 1
Base 10 to base 2 conversion is a recursive calculus: you have to divide the decimal number for a power-of-two and verify whether it is a multiple of two or not; if yes, the binary digit is 0, otherwise is 1.
Python doesn't recognize base 2 numbers as a type of data, and so a good compromise is to treat them as strings.
Here is a working implementation in Python:
def binaryConverter(decimalInteger, bitResolution):
binary = ""
n = 0
for n in range(bitResolution):
n = bitResolution - 1 - n
binary += str(decimalInteger // (2 ** n) % 2)
return binary
+ 1
Check this out:
https://code.sololearn.com/c5HDM15OYc03/?ref=app
0
# There is a simpler conversion technique
# for any number in the range you are examining
bin(255)
#you could put it in your function if you want to experiment
# with formatting the output
def conv(num):
'''
1-gets binary representation
2-slices off prefix
3-prefixes with Zero's
'''
print(bin(num)[2:].zfill(8))
#test
conv(255)
conv(34)
conv(0)