0

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?

2 Answers 2

4

Assuming number is in base 16, then this function returns the int equivalent of the number.

See this definition of int method

Sign up to request clarification or add additional context in comments.

1 Comment

The number is converted from, not to, hexadecimal.
3

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

1 Comment

Why is this comment receiving negative vote? The OP did ask for other methods of doing this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.