[英]Remove trailing zeros from binary result in python
我們有一個將十進制轉換為二進制的程序。
目標是運行程序,輸入一個值,然后以二進制形式輸出該值。
我的代碼的問題在於它在輸出二進制文件時有尾隨零。
我需要在不使用“數學”等外部庫的情況下實現這一點,所以請堅持使用內置函數。
電流輸出:
Insert a value: 5 The number fits in 1 byte and is in binary: 00000101 Insert a value: 100 The number fits in 1 byte and is in binary: 01100100 Insert a value: 280 The number fits in 16 bits and is in binary: 0000000100011000
預期輸出:
Insert a value: 5 The number fits in 1 byte and is in binary: 101 Insert a value: 100 The number fits in 1 byte and is in binary: 1100100 Insert a value: 280 The number fits in 16 bits and is in binary: 100011000
當前代碼:
def dec2bin(value, number_bits):
result = ''
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
else:
result = result + '0'
number_bits = number_bits - 1
print(result)
input_ok = False
userinput = 0
while not input_ok:
print('Insert a value:')
userinput = int(input())
if userinput > 65535:
print('invalid, cant handle that big numbers, try again')
else:
input_ok = True
if userinput < 256:
print('The number fits in 1 byte and is in binary:')
dec2bin(userinput, 8)
else:
print('The number fits in 16 bits and is in binary:')
dec2bin(userinput, 16)
使用字符串格式化函數很容易(請參閱 Pranav 的評論)。 但也許在這種情況下,您希望算法處理它,並將其視為字符串是作弊。
def dec2bin(value, number_bits):
result = ''
starting = True
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
starting = False
elif not starting:
result = result + '0'
number_bits = number_bits - 1
print(result)
由於您將值存儲為字符串,因此您可以使用
result.lstrip('0')
從您的答案中刪除前導零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.