hex -> 16bit signed int (newbie)
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Apr 15 07:47:18 EDT 2003
"zif" <zf_acs at DELETETHIShotmail.com> wrote in
news:TTRma.1502$KH1.321574 at news20.bellglobal.com:
> How can I get 16bit signed int from a hex string?
> Eval('0x...') gives me 16bit unsigned,
> 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).
>
How about this?
>>> def signedFromHex16(s):
v = int(s, 16)
if not 0 <= v < 65536:
raise ValueError, "hex number outside 16 bit range"
if v >= 32768:
v = v - 65536
return v
>>> signedFromHex16("ffff")
-1
>>> signedFromHex16("8000")
-32768
>>> signedFromHex16("7fff")
32767
>>>
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list