1

I am having string of four hex numbers like:

"0x00 0x01 0x13 0x00" 

which is equivalent to 0x00011300. How i can convert this hex value to integer?

glennsl
  • 28,186
  • 12
  • 57
  • 75
  • Possible duplicate of [How to get hex string from signed integer](http://stackoverflow.com/questions/228702/how-to-get-hex-string-from-signed-integer) – Danieboy Jan 31 '17 at 14:15

3 Answers3

3

Since you are having string of hex values. You may remove ' 0x' from the string to get the single hex number string. For example:

my_str =  "0x00 0x01 0x13 0x00"
hex_str = my_str.replace(' 0x', '')

where value hold by hex_str will be:

'0x00011300'   # `hex` string

Now you may convert hex string to int as:

>>> int(hex_str, 16)
70400
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1
>>> s="0x00 0x01 0x13 0x00"
>>> a=0
>>> for b in s.split():
...    a = a*256 + int(b,16)
... 
>>> a
70400
>>> hex(a)
'0x11300'
stark
  • 12,615
  • 3
  • 33
  • 50
0

The answer is here Convert hex string to int in Python.

Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:

x = int("deadbeef", 16)

With the 0x prefix, Python can distinguish hex and decimal automatically.

print int("0xdeadbeef", 0)
3735928559

print int("10", 0)
10

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; omitting the second parameter means to assume base-10. See the comments for more details.)

Community
  • 1
  • 1