Create function hexadecimal and octal conversion function in python

Asked

Viewed 2,157 times

2

Good evening, I’m trying to do two functions one to convert hexadecimal numbers into decimals and one to convert octal numbers into decimals, this is my code:

def hexadecimalparadecimal(n):
    decimal = 0
    n = str(n)
    n = n[::-1]
    tam = len(n)
    num = list("0123456789ABCDEF")
    for i in range(tam):
        if n[i] == '1':
            decimal = decimal + 16**i
            print('EM DECIMAL: {}'.format (decimal))
    return decimal

The problem that the conversion is wrong, when I compare the string with a 1 this all well, but I still could not use all values, I tried to put the values in a list and compare but gave error, besides I tried to do A = 10, B = 11 but I still could not type the letter receiving its values, in the octal I do not have this problem with letters but I still could not sum all values, use the numbers of the list, someone knows how to use the list in this case?

2 answers

2

Good afternoon, champ, all right?

Do you really want to do it this way, say "in the nail" ? For python already has functions implemented for such a task.

It is usually done as shown below, in a more pythonic way.

Hex to Dec

def hexadecimalparadecimal(numero):
    convertido = int(numero,16)
    return convertido

Oct for Dec

def octalparadecimal(numero2):
    convertido2 = int(numero2,8)
    return convertido2

Just call the function and give a quote value, example :

inserir a descrição da imagem aqui

In case you want more codes on "nail" I found some over octal to decimal on this English stack topic : Octal>Decimal

Hug.

Claudio.

  • Yes, in case it would be in the nail without native functions.

0


Talk Danilo, got it, see if this code below that cool, it is in the topic I told you about before.

def todec2(hexa):
    x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
         'A', 'B', 'C', 'D', 'E', 'F']
    hexalista = list(hexa) #passa para lista 
    resultado = 0
    for pos, digit in enumerate(hexalista[-1::-1]): 
        posicao = x.index(digit)
        resultado = (int(posicao) * (16**pos)) + resultado
    return(resultado)

Here’s the thing, on the loop for the function enumerate indexes the past number, which was already a list, making for example the hexadecimal '2E' of:

inserir a descrição da imagem aqui

In :
inserir a descrição da imagem aqui

So now I have position(pos) and the digit(digit) corresponding that position, where for values above 9, the values 11,12,13... will be assigned due to the numerical index, which kills its question of assigning values to letters.

In this way we assign the variable posicao the index of the digit (what position it is in the list) and then we leave for the account.

The variable resultado then receives the operations where the posicao multiplies base 16 to variable pos remembering that this is the loop iterator and starts at 0, in the next loop pos will be 1 and so on.

The "trick" to such regularity is the ordination made on the list with [-1::-1] which reverses the list and first iterates the least significant digit, which in the conversion rule receives 16 0, then the most significant digits receive 16 1.16 2, and so on.

An example to illustrate the values, let’s suppose that want to convert '2E'(16), whose result is 46(10), notice the values that the variables mentioned above take.

inserir a descrição da imagem aqui

Another example of pythonian witchcraft is the code below, which I couldn’t understand yet haha, hug.

def hexToDec(hexi):
result = 0;
for ch in hexi:
if 'A' <= ch <= 'F':
  result = result * 16 + ord(ch) - ord('A') + 10
else:
  result = result * 16 + ord(ch) - ord('0')
return result;

python Hex to decimal using for loop

Browser other questions tagged

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