0

I'm having trouble trying to create a function that converts positive decimal numbers into a hex string (without printing, just returning the string with hex number)

A function that converts binary to hex string should work to, if you think it's easier

I've already tried some codes I've found in the forum, but none of them worked properly, some just worked for numbers in the 0-15 interval and then started to print from 0 again.

def hex(n):
    r = ''
    if n < 16:
        if n < 10: return r + str(n)
        if n == 10: return r + 'A'
        if n == 11: return r + 'B'
        if n == 12: return r + 'C'
        if n == 13: return r + 'D' 
        if n == 14: return r + 'E'
        if n == 15: return r + 'F'
    else:
        hex(n//16)

Thats the code I've said that works just til dec 15

The code need to receive a decimal or a binary number (if it's easier), and return a string with number converted in hex.

Edit: I can't use hex() bin(), dec()...

2 Answers2

0

You could use a while loop instead of recursion, and use a dict to map values of the remainder of the division of n by 16 (not the quotient, the quotient is used as the next value of n) to the corresponding hex digit:

def my_hex(n):
  m = {i : str(i) for i in range(10)}
  m.update({
    10: 'A',
    11: 'B',
    12: 'C',
    13: 'D',
    14: 'E',
    15: 'F',
  })
  r = ''
  while n:
    r = m[n % 16] + r
    n //= 16
  return r
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

You only need return hex(n//16) + hex(n%16) in the else condition :

def hex(n):
    r = ''
    if n < 10: return r + str(n)
    if n == 10: return r + 'A'
    if n == 11: return r + 'B'
    if n == 12: return r + 'C'
    if n == 13: return r + 'D' 
    if n == 14: return r + 'E'
    if n == 15: return r + 'F'

    else:
         return hex(n//16) + hex(n%16)

Example:

hex(5678)

Output:

'162E'

when you convert the number 90 for example to hexadecimal you need 5x16 +10. Then on a recurring basis you need that the function returns the conversion to decimal of n // 16 but also from the rest of the division.

and considering that you can concatenate str simply with the sum operator, you only need to add hex(n%16)

ansev
  • 30,322
  • 5
  • 17
  • 31