简体   繁体   English

从python中的二进制结果中删除尾随零

[英]Remove trailing zeros from binary result in python

We have a program that changes decimals to binary.我们有一个将十进制转换为二进制的程序。
And the goal is to run the program, input a value, and outputs the value in binary.目标是运行程序,输入一个值,然后以二进制形式输出该值。

The problem with my code is that it has trailing zeros when outputting the binary.我的代码的问题在于它在输出二进制文件时有尾随零。
I need to achieve this without using external libraries like "math", so please stick to the built-in functions.我需要在不使用“数学”等外部库的情况下实现这一点,所以请坚持使用内置函数。

Current output:电流输出:

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

Expected output:预期输出:

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

Current code:当前代码:

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)

It easy with string formatting functions (see Pranav's comment).使用字符串格式化函数很容易(请参阅 Pranav 的评论)。 But perhaps in this case you want the algorithm to take care of it, and see treating it as a string is cheating.但也许在这种情况下,您希望算法处理它,并将其视为字符串是作弊。

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)

Since you are storing the value as a string you can use由于您将值存储为字符串,因此您可以使用

result.lstrip('0')

to remove the leading zeros from your answer.从您的答案中删除前导零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM