hex to bin 16 bit word
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Apr 27 15:09:29 EDT 2012
On Fri, 27 Apr 2012 11:56:45 -0700, Paul Rubin wrote:
> python <w.g.sneddon at gmail.com> writes:
>> What to decode hex '0xC0A8' and return signed short int.
>
> Is this right?
>
> n = int('0xC0A8', 16)
> if n >= 0xffff:
> n -= 0x10000
No.
>>> struct.unpack('>h',b'\xC0\xA8')
(-16216,)
>>> n = int('0xC0A8', 16)
>>> if n >= 0xffff:
... n -= 0x10000
...
>>> n
49320
Should be -16216.
Personally, I don't see why the OP doesn't just use struct.unpack to
unpack a struct.
--
Steven
More information about the Python-list
mailing list