Click here to Skip to main content
16,016,227 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to convert decimals to binary and binary to decimals but i get all the time wrong answers. I am not allowed to use bin and other built in statements in Pycharm that could help me to convert answer.

Python
"""Converter."""


def dec_to_binary(dec: int) -> str:
    """
    Convert decimal number into binary.

    :param dec: decimal number to convert
    :return: number in binary
    """
    if dec > 1:
        dec_to_binary(dec // 2)
        print(dec % 2, end='')
        return
def binary_to_dec(binary: str) -> int:
    """
    Convert binary number into decimal.

    :param binary: binary number to convert
    :return: number in decimal
    """
    decimal, i, n = 0, 0, 0
    while (binary != 0):
        dec = binary % 10
        decimal = decimal + dec * pow(2, i)
        binary = binary // 10
        i += 1
    print(decimal)


if __name__ == "__main__":
    print(dec_to_binary(145))  # -> 10010001
    print(dec_to_binary(245))  # -> 11110101
    print(dec_to_binary(255))  # -> 11111111

    print(binary_to_dec("1111"))  # -> 15
    print(binary_to_dec("10101"))  # -> 21
    print(binary_to_dec("10010"))  # -> 18


What I have tried:

I have tried these codes but i usually get 2 decimals working, in the end it says for example 100011 and None...
Posted
Updated 11-Sep-19 22:55pm
v2

Sure, I can just give you a full blowup solution, but I am not sure you will learn something. As it is very basic understanding of Python and programming, I think it is better to give you leads and a link to a good tutorial.
Python
# Because of
    print(dec_to_binary(145))  # -> 10010001
# and
    print(binary_to_dec("1111"))  # -> 15
# you need to define functions with "return values" instead of print the partial result

Read this page and pay attention to "Return Values" and "Recursion": Python Functions[^]
-----
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

27.3. pdb — The Python Debugger — Python 3.6.1 documentation[^]
Debugging in Python | Python Conquers The Universe[^]
pdb – Interactive Debugger - Python Module of the Week[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
v2
Try the following. You may need to modify some part of it to meet your own criteria, but it does the basics.
Python
def binary_to_dec(binary: str) -> int:
    """
    Uses the ord() builtin to get the numeric value of a character
    Subtracting the ord('0') gets the integer value of the digit
    """
    tot = 0;
    for i in binary[:]:
        num = ord(i) - ord('0')
        tot *= 2
        tot += num
    return tot

def dec_to_binary(dec: int) -> str:
    """
    Adds the ord('0') to 0 or 1 to get the value of the digit
    and uses the chr() builtin to convert back to a character
    """
    bin = ""
    while dec != 0:
        num = (dec & 1) + ord('0')
        bin = chr(num) + bin
        dec >>= 1
    return bin
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900