Archives / Search ›

hex to string?

So I had a string I really needed to retrieve (a serial number that I appear to have misplaced, and which the software conveniently forgot when I swapped hard drives) which was stored in the app’s plist as a large ASCII-encoded hexadecimal number. Turning it into a string should have been easy, and I still maintain it is, but in my late-night torpor this is the best I could come up with:

In [41]: s = '30798C86...'

In [42]: l = [int(''.join(i), 16) for i in zip(s[::2], s[1::2])]
Out[42]: [48, 121, 140, 134, ...]

In [43]: struct.pack('B' * len(l), *l)
Out[43]: '0y\x8c\x86...'

at which point I realized that didn’t look anything like a serial number, so I’ll have to call my parents in the morning to see if they can find the box for said software (thanks, Apple). Still, there must be a better way to do this in Python without explicitly looping through the string.

Update: I asked on IRC, and got:

23:49  bdash> sabi: s.decode('hex') maybe?
23:49  sabi> !!!
23:49  sabi> yes, that's perfect
23:49  bdash> :-)

Thanks Mark.

No comments yet. Be the first.

Leave a reply