Decimal to hexadecimal conversion

I am needing to do an algorithm in python to make a decimal to hex converter. But I can't use ifs and neither ready functions, type 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 to hexadecimal, but that would be a ready function and that's not what I want. Is there a way to do this? 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="")
Author: MagicHat, 2017-06-30

2 answers

Can do 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 in Ideone

 0
Author: MagicHat, 2017-07-01 02:44:42

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

Or excerpt:

>>> int2hex(10)
'A'

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

In 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 the hexadecimal values.

No stretch:

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

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

Na Line:

result.reverse()

I invert the values stored in the list.

And last on the line:

return ''.join(result)

I convert the list to string and return it as a response.

How to run the snippet:

print(int2hex(64202))

Results in 'knife'

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

Complete 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'))
 0
Author: britodfbr, 2017-07-10 15:26:58