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>You may convert the <code>binary</code> string to <code>hex</code> string (without using <code>hex()</code> function) as:</p>

<pre><code>&gt;&gt;&gt; binary_string = '0000010010001101'
&gt;&gt;&gt; '%0*X' % ((len(binary_string) + 3) // 4, int(binary_string, 2))
'048D'
</code></pre>

<p>There is simpler way to convert <code>binary</code> to <code>hexadecimal</code> using <code>hex()</code> which might be useful for someone else:</p>

<pre><code>&gt;&gt;&gt; hex(int('010110', 2))
'0x16'
</code></pre>

python computer-science