hex -> 16bit signed int (newbie)
Steven Taschuk
staschuk at telusplanet.net
Tue Apr 15 12:46:11 EDT 2003
Quoth zif:
> How can I get 16bit signed int from a hex string?
> Eval('0x...') gives me 16bit unsigned,
... which you could easily convert to signed.
def hex2uint16(s):
# assumed s is up to four hex digits
i = eval('0x' + s)
if i >= 2**15:
i -= 2**16
return i
> struct.pack('i', '\x..\x..') works fine, but
> Python doesn't allow me to concatenate strings
> with '\' (str(92) gives me '\\', which doesn't
> work as well).
To be clear: concatenating strings containing backslashes is fine.
What you want, however, is to construct on the fly a string
containing backslash-escapes, and have those escapes interpreted
the same way they would be in source. That calls for an eval.
>>> hexstr = 'AB0E'
>>> s = ''
>>> for i in range(0, len(hexstr), 2):
... s += '\\x%s' % hexstr[i:i+2]
...
>>> s
'\\xAB\\x0E'
>>> eval('"' + s + '"')
'\xab\x0e'
But there's an easier way:
>>> hexstr = 'AB0E'
>>> import binascii
>>> binascii.unhexlify(hexstr)
'\xab\x0e'
Whereupon you can do your struct.unpack trick if you want.
(Though you should be aware that the meaning of 'i' is
machine-dependent; on my machine it's 32 bits, for example. If
you want 16-bit unsigned on all machines, you want '>h' or some
such. See the struct module's documentation.)
--
Steven Taschuk 7\ 7'Z {&~ .
staschuk at telusplanet.net Y r --/hG-
(__/ )_ 1^1`
More information about the Python-list
mailing list