Reputation: 2217
Byte string to long value:
I have a string of Hex values, as in ',ff,fe,d0,ea', how do I convert these to a (big-endian) long value? Code snippet:
dataStr = ',ff,fe,d0,ea'
dataVal = struct.unpack('>l', '\xff\xfe\xd0\xea')[0]
print dataStr, ' = ', dataVal # prints out ,ff,fe,d0,ea = -77590
I think \
is an unprintable char, so I believe my question is really (given the snippet), how do I convert from ,ff,fe,d0,ea
to \xff\xfe\xd0\xea
? or any array values suitable for the struct.unpack
function?
Upvotes: 1
Views: 211
Reputation: 43024
Here is a line that will do the conversion to to a hex string suitable for unpacking.
hexstr = "".join([chr(int(ss, 16)) for ss in dataStr.split(",") if ss])
Often when you have hex strings like this what you really want is an unsigned integer. So, to get that with unpack you do this:
myval = struct.unpack(">I", hexstr)[0]
Now you have 4294889706 as the result.
But in the first line you already had integers, so you could also shift and them yourself. Here's how you can do that.
res = 0
for v in [int(ss, 16) for ss in dataStr.split(",") if ss]:
res <<= 8
res += v
Gets the same result.
Upvotes: 0
Reputation: 7149
The following will decode ',ff,fe,d0,ea'
to '\xff\xfe\xd0\xea'
dataStr = ',ff,fe,d0,ea'.replace(',', r'\x').decode('string-escape')
Upvotes: 4