Python Forum
decimal or hexadecimal digits to int - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: decimal or hexadecimal digits to int (/thread-5268.html)



decimal or hexadecimal digits to int - Skaperen - Sep-25-2017

i want to convert a string of digits to an int like int() does.  the digits will be decimal by default except if prefixed by '0x' or '0X' then they are hexadecimal, or if prefixed by '0o' or '0O' then octal, or if prefixed by '0b' or '0B' then binary.  is there any built-in way or do i need to code my own?  C can do this at least for decimal and  hexadecimal.


RE: decimal or hexadecimal digits to int - ichabod801 - Sep-26-2017

eval will do it. However, if you don't have control over your input stream, eval is a security risk. You would either want a regex to confirm it's just a number, or you would want to do a conditional and just convert with int using the base parameter.


RE: decimal or hexadecimal digits to int - hbknjr - Sep-26-2017

The python int() function takes in a base parameter which converts to object/string to base 10 from the given base.
So int('101',2) = 5.

Here's one way you can write you program

def convertToInt(num_string):
    determine_base ={'0x':16,'0b':2,'0o':8} # dict to detrmine base

    # returns base from dict defaults to None(for base 10)
    base = determine_base.get(num_string[:2].lower(),None) 

    if base != None:
        return int(num_string[2:],base)
    else:
        return int(num_string)
        
# prefix '0x' & '0X' => hexadecimal, '0b' & '0B' => binary, '0O' and '0o' => Octal
strings = ['0xd4','0B10001','0o763','56'] 

for num in strings:
    print(convertToInt(num))



RE: decimal or hexadecimal digits to int - Skaperen - Sep-26-2017

(Sep-26-2017, 06:58 AM)hbknjr Wrote: The python int() function takes in a base parameter which converts to object/string to base 10 from the given base.
So int('101',2) = 5.

Here's one way you can write you program

def convertToInt(num_string):
determine_base ={'0x':16,'0b':2,'0o':8} # dict to detrmine base

# returns base from dict defaults to None(for base 10)
base = determine_base.get(num_string[:2].lower(),None)

if base != None:
return int(num_string[2:],base)
else:
return int(num_string)

# prefix '0x' & '0X' => hexadecimal, '0b' & '0B' => binary, '0O' and '0o' => Octal
strings = ['0xd4','0B10001','0o763','56']

for num in strings:
print(convertToInt(num))
something like that was what i had in mind.