0

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

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Since you are storing the value as a string you can use

result.lstrip('0')

to remove the leading zeros from your answer.

1 Comment

@kabax this is in the accepted answer in my linked duplicate. Please read linked questions / answers carefully. How much research effort is expected of Stack Overflow users?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.