Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String of bytes into an int

Tags:

python

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

like image 226
Miscreant Avatar asked Dec 15 '22 14:12

Miscreant


1 Answers

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'
like image 85
Ashwini Chaudhary Avatar answered Dec 21 '22 11:12

Ashwini Chaudhary