2

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:

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) < baseten:      # Determines beginning value of exponent
        x+=1

    while x >= 0:
        value = int(baseten/16**x)

        if value < 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

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.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Mitch Howe
  • 55
  • 1
  • 6
  • 3
    @Robᵩ the OP says that the program is not working for binary numbers that are more than 5 digits long and wants help understanding why. – Robert Columbia Aug 25 '16 at 19:48
  • 3
    How does 01101 become 16? – FamousJameous Aug 25 '16 at 19:49
  • I would suggest that rather than doing such complicated math that you iterate over nibbles (4 bits) and apply your method for converting to a hexadecimal character – bravosierra99 Aug 25 '16 at 19:51
  • Your conversion to base 10 as mentioned is off, I believe you want something like: `baseten = int(baseten + binary[i] * 2**(len(binary)-i-1))` because you are working from left to right, so you actually want to count down `len(binary)-i-1` – depperm Aug 25 '16 at 19:53
  • 2
    also, a fun little trick is that if your value is > 9 < 16, you can simply print(chr(ord('A')-10 + value)) It helps get rid of the giant if tree you have going on. – bravosierra99 Aug 25 '16 at 19:55
  • Possible duplicate of [Python - Homework - Converting Any Base to Any Base](http://stackoverflow.com/questions/3973685/python-homework-converting-any-base-to-any-base) – Noctis Skytower Aug 25 '16 at 20:10

3 Answers3

2

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

As others have noticed, the logic for base 10 conversion is off. A binary string of 01101 is equivalent to 13 in base ten, and D 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 len(binary) - 1 - i instead of i in your conversion loop:

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

Your second problem is that baseten-=int(16**x) should be baseten -= value*(16**x).

These changes will correctly return D6 for a binary string of 11010110.

Karin
  • 8,404
  • 25
  • 34
0

You may convert the binary string to hex string (without using hex() function) as:

>>> binary_string = '0000010010001101'
>>> '%0*X' % ((len(binary_string) + 3) // 4, int(binary_string, 2))
'048D'

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

>>> hex(int('010110', 2))
'0x16'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

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:

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 >= 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()
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117