Naga Suresh.Thota
Naga Suresh.Thota

Reputation: 45

Python: convert string of multiple hexadecimal values to integer

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?

Upvotes: 1

Views: 3114

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

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

Upvotes: 3

user6037100
user6037100

Reputation:

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.)

Upvotes: 0

stark
stark

Reputation: 13189

>>> s="0x00 0x01 0x13 0x00"
>>> a=0
>>> for b in s.split():
...    a = a*256 + int(b,16)
... 
>>> a
70400
>>> hex(a)
'0x11300'

Upvotes: 1

Related Questions