简体   繁体   中英

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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