Mike
Mike

Reputation: 1008

How to convert hex string to integer in Python?

How to convert

x = "0x000000001" # hex number string

to

y = "1"

Upvotes: 4

Views: 12226

Answers (5)

jimmy240341
jimmy240341

Reputation: 1

you can do:

y = int(x, 0)  # '0' ;python intepret x according to string 'x'.

In the offical documentation, it is explained as "If base is zero, the proper radix is determined based on the contents of the string;"

Upvotes: 0

Supot Sawangpiriyakij
Supot Sawangpiriyakij

Reputation: 111

Python 2.7 have a problem to convert hex from read binary file

Python 3 not have this problem

f=open(file_name,'rb')
raw = f.read()

print int(raw[6])    #error invalid literal for int with base 10:
print ord(raw[6])    #Work

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319879

>>> int("0x000000001", 16)
1

Upvotes: 2

codaddict
codaddict

Reputation: 455350

You can do:

y = int("0x000000001", 16)

in your case:

y = int(x, 16)

Looks like you want the int converted to string:

y = str(int(x, 16))

Upvotes: 14

Felix Kling
Felix Kling

Reputation: 816930

Use int() and provide the base which your number is in (in your case 16).
Then apply str() to convert it back to a string:

y = str(int(x, 16))

Note: If you omit the base then the default base 10 is used which would result in a ValueError in your case.

Upvotes: 4

Related Questions