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:
In :
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.
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
Yes, in case it would be in the nail without native functions.
– Danilo Costa