4

How to convert

x = "0x000000001" # hex number string

to

y = "1"

5 Answers 5

14

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))
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

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

Comments

0

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

Comments

0

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;"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.