Converting binary numbers to hexadecimal in Python not working for more than 5 digits (Homework)
<p>I have an assignment from my computer science teacher to make a program that converts a binary number to hexadecimal using Python. I have made it so that the binary properly converts to base ten/decimal and the decimal properly converts to hex, but  it only works if the binary number is less than 5 digits (i.e. 01101 correctly turns out 16 and 11111 turns 1F, but something like 11010110 stupidly becomes "6") Here's my code:</p>

<pre><code>def main():
    print("Convert binary numbers to hexadecimal.")

    binary = list(input("Enter a binary number: "))     # User input

    for i in range(len(binary)):    # Convert binary to list of integers
        binary[i] = int(binary[i])

    baseten = 0

    for i in range(len(binary)):    # Converts binary to base ten
        baseten = int(baseten + binary[i] * 2**i)

    x = int(0)
    while 16**(x+1) &lt; baseten:      # Determines beginning value of exponent
        x+=1

    while x &gt;= 0:
        value = int(baseten/16**x)

        if value &lt; 10:
            print(value, end="")
        if value == 10:
            print("A", end="")
        if value == 11:
            print("B", end="")
        if value == 12:
            print("C", end="")
        if value == 13:
            print("D", end="")
        if value == 14:
            print("E", end="")
        if value == 15:
            print("F", end="")

        baseten-=int(16**x)

        x-=1
</code></pre>

<p>NOTE - I know Java pretty well, I've had over a year of experience with it, so don't expect not to understand something that is a bit complicated. Also the goal is not just to use the hex() function.</p>

<p>The following program can convert binary numbers into hexadecimal numbers, but it can also convert from and to other bases as well depending on the settings that you provide in your code:</p>

<pre><code>import string


TABLE = string.digits + string.ascii_uppercase


def main():
    initial_variable = input('Please enter a number: ')
    base_variable = 2
    convert_variable = 16
    integer = str_to_int(initial_variable, base_variable)
    hexadecimal = int_to_str(integer, convert_variable)
    print(hexadecimal)


def str_to_int(text, base):
    integer = 0
    for character in text:
        if character not in TABLE:
            raise ValueError('found unknown character')
        value = TABLE.index(character)
        if value &gt;= base:
            raise ValueError('found digit outside base')
        integer *= base
        integer += value
    return integer


def int_to_str(integer, base):
    array = []
    while integer:
        integer, value = divmod(integer, base)
        array.append(TABLE[value])
    return ''.join(reversed(array))


if __name__ == '__main__':
    main()
</code></pre>

python computer-science