Decimal to hexadecimal conversion

Asked

Viewed 5,037 times

1

I need to do a python algorithm to make a decimal to hexadecimal converter. But I can’t use ifs or ready-made functions, like Hex(). I did, but when I went to print the value in hexa I used print("%X"%h) to print the letters without using if, but I realized that this converts any number into hexadecimal, but that would be a ready function and that’s not what I want. Is there a way to do that? My code:

n = int(input())
r = []

while n > 0:
    r.append(n % 16)
    n = n // 16

for i in range(len(r)-1,-1,-1):
    print("%X"%r[i],end="")
  • I don’t quite understand, please go straight to the problem.

2 answers

0


You can do it like this :

hex = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"]
n = int(input("Digite um núemro inteiro: "))
r = []
while n > 0:
    r.append(hex[(n % 16)])
    n = n // 16
for i in range(len(r)-1,-1,-1):
    print(r[i],end="")

See on Ideone

  • Mass! was unable to think of a way to make decimal to hexadecimal conversion without using if, or a ready function. Thank you.

0

In this example below I used doctest to validate the results.

def int2hex(n):
    '''
    :param n: int
    :return: str
    >>> int2hex(10)
    'A'
    >>> int2hex(15)
    'F'
    >>> int2hex(32)
    '20'
    >>> int2hex(255)
    'FF'
    >>> int2hex(65535)
    'FFFF'
    '''

    x16 = '0 1 2 3 4 5 6 7 8 9 a b c d e f'.upper().split()
    result = []
    while n > 0:
        result.append(x16[(n % 16)])
        n = n // 16
    result.reverse()
    return ''.join(result)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

    print(int2hex(64202))

The excerpt:

>>> int2hex(10)
'A'

Refer to doctest calls, where in the first line is the method call and the second is the expected result.

On the line:

x16 = '0 1 2 3 4 5 6 7 8 9 a b c d e f'.upper().split()

I create a high box list with hexadecimal values.

In the stretch:

while n > 0:
    result.append(x16[(n % 16)])
    n = n // 16

I decompose base number 10 to base number 16, however it is stored in reverse.

On the line:

result.reverse()

I invert the values stored in the list.

and last in line:

return ''.join(result)

convert the list into string and return as response.

How to execute the excerpt:

print(int2hex(64202))

presents as a result 'KNIFE'

If it is necessary to input the values in the string format, one can add a casting and also exception handling.

Full example:

def int2hex(n):
    '''
    :param n: int
    :return: str
    >>> int2hex(10)
    'A'
    >>> int2hex(15)
    'F'
    >>> int2hex(32)
    '20'
    >>> int2hex(255)
    'FF'
    >>> int2hex(65535)
    'FFFF'
    '''

    x16 = '0 1 2 3 4 5 6 7 8 9 a b c d e f'.upper().split()
    result = []
    try:
        n = int(n)

        while n > 0:
            result.append(x16[(n % 16)])
            n = n // 16
        result.reverse()
    except ValueError as e:
        return ('Erro: %s' %e)
    except:
        raise
    else:
        return ''.join(result)

if __name__ == '__main__':
    import doctest
    doctest.testmod()


    print(int2hex(64202))
    print(int2hex('20'))
    print(int2hex('a'))
    print(int2hex('15'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.