Reputation: 365
So I have a code, but i'm not sure how it works:
def getValue(number):
return int(number,16)
So if I were to put in 'a25' for the number it should return 2597 But my question is how does this int function work, and is there another way to do this?
Upvotes: 0
Views: 360
Reputation: 43147
Assuming number is in base 16, then this function returns the int
equivalent of the number.
See this definition of int method
Upvotes: 4
Reputation: 7944
It works something like this:
import string
allChars = string.digits+string.lowercase #get a list of all the 'characters' which represent digits
def toInt(srep,base):
charMap = dict(zip(allChars,range(len(allChars)))) #map each 'character' to the base10 number
num = 0 #the current total
index = len(srep)-1 #the current exponent
for digit in srep:
num += charMap[digit]*base**index
index -= 1
return num
The process with some debugging print for interpreting 'a16' would be:
>>> int('a16',16) #builtin function
2582
>>> toInt('a16',16)
+=10*16^2 -> 2560
+=1*16^1 -> 2576
+=6*16^0 -> 2582
2582
Upvotes: 3