Skip to content Skip to sidebar Skip to footer

Writing A Function In Python 3 To Convert Base 16 To Base 10

Is there an easy way to modify this code which converts from base 2 into base 10 to work for converting base 16 into base 10? My objective is to build a dedicated function for conv

Solution 1:

Yikes.

int already can convert from any base to base 10 - just supply it as the second argument.

int('101010',2)
Out[64]: 42int('2A',16)
Out[66]: 42

Solution 2:

To convert hexadecimal string to int:

>>>hexstr = '101010'>>>int(hexstr, 16)
1052688

The same -- without int constructor:

>>>import binascii >>>int.from_bytes(binascii.unhexlify(hexstr), 'big')
1052688

The same -- similar to @SzieberthAdam's answer:

>>>hex2dec = {d: i for i, d inenumerate('0123456789abcdef')}>>>sum(hex2dec[h] * 16**pos for pos, h inenumerate(reversed(hexstr.lower())))
1052688

or:

>>>from functools import reduce>>>reduce(lambda n, h: n*16 + hex2dec[h], hexstr.lower(), 0)
1052688

that is equivalent to:

def hex2int(hexstr):
    n =0for h in hexstr.lower():
        n = n*16 + hex2dec[h]
    return n

Example:

>>>hex2int('101010')
1052688

As an alternative, one could convert all digits to int first:

>>>reduce(lambda n, d: n*16 + d, map(hex2dec.get, hexstr.lower()))
1052688

It raises TypeError for empty strings.

Solution 3:

Well, here you go then:

>>>binary_num = '101010'>>>sum(int(b)*2**i for i, b inenumerate(reversed(binary_num)))
42

Post a Comment for "Writing A Function In Python 3 To Convert Base 16 To Base 10"