4

I want to convert a string like this into an int: s = 'A0 00 00 00 63'. What's the easiest/best way to do that?

For example '20 01' should become 8193 (2 * 16^3 + 1 * 16^0 = 8193).

2 Answers 2

12

Use int() with either str.split():

In [31]: s='20 01' In [32]: int("".join(s.split()),16) Out[32]: 8193 

or str.replace() and pass the base as 16:

In [34]: int(s.replace(" ",""),16) Out[34]: 8193 

Here both split() and replace() are converting '20 01' into '2001':

In [35]: '20 01'.replace(" ","") Out[35]: '2001' In [36]: "".join('20 01'.split()) Out[36]: '2001' 
Sign up to request clarification or add additional context in comments.

Comments

0
>>> s = 'A0 00 00 00 63' >>> s = s.replace(" ","") >>> print s A000000063 >>> for i in xrange(0,len(s),4): print int(s[i:i+3],16) 2560 0 99 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.