How to convert a hexadecimal string to an integer in Python?

How to convert

x = "0x000000001" # hex number string 

to

 y = "1" 
+4
source share
5 answers

You can do:

 y = int("0x000000001", 16) 

in your case:

 y = int(x, 16) 

It looks like you want the int to convert to a string:

 y = str(int(x, 16)) 
+14
source

Use int() and specify the base where your number is located (in your case 16 ).
Then apply str() to convert it to a string:

 y = str(int(x, 16)) 

Note. If you omit the base, the default base is 10 , which will result in a ValueError in your case.

+4
source
 >>> int("0x000000001", 16) 1 
+2
source

Python 2.7 has a problem converting hex from a binary read file

Python 3 does 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 
0
source

You can do:

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

In official documentation, this is explained as follows: "If the base is zero, then the correct root is determined based on the contents of the string;"

0
source

Source: https://habr.com/ru/post/1306901/


All Articles