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>I'm going to focus on helping you debug what's going wrong in your code as opposed to suggesting an alternative way to do it. It is homework after all :)</p>

<p>As others have noticed, the logic for base 10 conversion is off. A binary string of <code>01101</code> is equivalent to <code>13</code> in base ten, and <code>D</code> in hex. This is because you need to iterate through your binary string starting at the least significant digit. Without changing your code too much, you can do this by indexing to <code>len(binary) - 1 - i</code> instead of <code>i</code> in your conversion loop:</p>

<pre><code>for i in range(len(binary)):    # Converts binary to base ten
    baseten = int(baseten + binary[len(binary) - 1 - i] * 2**i)
</code></pre>

<p>Your second problem is that <code>baseten-=int(16**x)</code> should be <code>baseten -= value*(16**x)</code>.</p>

<p>These changes will correctly return <code>D6</code> for a binary string of <code>11010110</code>.</p>

python computer-science