Create function of hexadecimal and octal conversion function in python

1

Good night, I'm trying to do two functions one to convert hexadecimal numbers to decimals and one to convert octal numbers to 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 is fine, but I still could not use all the values, I tried the values in a list and compare but it gave error, in addition I tried to make A = 10, B = 11 even more I could not enter the letter receiving its values, in octal I do not have this problem with letters but I have not been able to do the sum of all values, use the numbers in the list, someone knows how to use the list in this case?

    
asked by anonymous 10.01.2018 / 04:27

2 answers

0

Speak Danilo, I understood, see if this code below that cool, it is in the topic that I told you earlier.

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)

It is as follows, in the for loop, the enumerate function indexes the last number, which already was a list, making for example the hexadecimal '2E' of:

In:

Then,Inowhaveaposition(pos)andthedigit(digit)correspondingtothatposition,whereforvaluesabove9,values11,12,13willbeassignedduetothenumericindex,thewhichkillsyourissueofassigningvaluestotheletters.

Inthiswayweassignthevariableposicaotheindexofthedigit(whatpositionitisinthelist)andthenwegototheaccount.

Theresultadovariablethenreceivesoperationswhereposicaomultipliesbase16toposrememberingthatthisistheiteratoroftheloopandstartsat0,inthenextloopposwillbe1andsoonagainst.

The"trick" for such regularity is the ordering in the list with [-1::-1] which inverts the list and iterates first 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 assume that I want to convert '2E' (16), whose result is 46 (10), notice the values that the commented variables above take.

AnotherexampleofPythonwitchcraftisthecodebelow,whichIcouldnotunderstandyethaha,hug.

defhexToDec(hexi):result=0;forchinhexi:if'A'<=ch<='F':result=result*16+ord(ch)-ord('A')+10else:result=result*16+ord(ch)-ord('0')returnresult;

python hex to decimal using for loop

    
12.01.2018 / 00:10
0

Good afternoon champ, okay?

Do you really want to do it this way, let's say "on the nail"? Because python already has functions implemented for such a task.

Usually done as shown below, in a more pythonic way.

Hex to dec

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

Oct to dec

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

Just call the function and give it a quotation mark, for example:

Ifyouwantmorecodesonthe"nail" I found some about octal to decimal in this English stack topic: Octal & Decimal

Thank you.

Claudio.

    
10.01.2018 / 19:23