Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse hex or decimal int in Python [duplicate]

Tags:

python

I have a string that can be a hex number prefixed with "0x" or a decimal number without a special prefix except for possibly a minus sign. "0x123" is in base 16 and "-298" is in base 10.

How do I convert this to an int or long in Python?

I don't want to use eval() since it's unsafe and overkill.

like image 381
Hein Avatar asked Mar 02 '09 22:03

Hein


People also ask

How do you parse a hex in Python?

To convert a hexadecimal string to an integer, pass the string as a first argument into Python's built-in int() function. Use base=16 as a second argument of the int() function to specify that the given string is a hex number.

Can Python convert hex to decimal?

Python module provides an int() function which can be used to convert a hex value into decimal format. It accepts 2 arguments, i.e., hex equivalent and base, i.e. (16). int() function is used to convert the specified hexadecimal number prefixed with 0x to an integer of base 10.

How do you parse an integer in Python?

Parse int to string in Python We can use the inbuilt str() function to parse Python int to String to convert an integer to String. Parsing is the same as converting in programming.

What is Python base16?

In base 16 (also called "hexadecimal" or "hex" for short) you start at 0 then count up 0123456789ABCDEF (16 digits in total). The int function accepts any number from 2 and 36 as the base, it just extends the alphabet: base 36 is 0123456789ABCEDFGHIJKLMNOPQRSTUVWXYZ .


2 Answers

int("0x123", 0) 

(why doesn't int("0x123") do that?)

like image 87
Hein Avatar answered Sep 21 '22 23:09

Hein


Base 16 to 10 (return an integer):

>>> int('0x123', 16) 291 

Base 10 to 16 (return a string):

>>> hex(291) '0x123' 
like image 42
riza Avatar answered Sep 23 '22 23:09

riza