two's complement bytes
castironpi
castironpi at gmail.com
Sun Aug 24 00:23:19 EDT 2008
On Aug 23, 10:51 pm, "Adam W." <AWasile... at gmail.com> wrote:
> I'm dabbling with AVR's for a project I have and that means I have to
> use C (ageist my will). Because my AVR will be tethered to my laptop,
> I am writing most of my logic in python, in the hopes of using at
> little C as possible.
>
> In my quest I came across a need to pass a pair of sign extended two's
> complement bytes. After painfully reading the wikipedia article on
> what two's complement was, I then thought of how I would handle this
> in python. I don't really recall ever having to work in binary with
> python, so I really am clueless on what to do.
>
> I can feed python either two hex bytes or binary, but how do I convert
> it into an int, and more importantly how do I make sure it handles the
> sign properly?
Try this out. Does it come close to what you want?
import struct
struct.pack( 'i', ~10 )
~struct.unpack( 'i', _ )[ 0 ]
>>> import struct
>>> struct.pack( 'i', ~10 )
'\xf5\xff\xff\xff'
>>> ~struct.unpack( 'i', _ )[ 0 ]
10
>>>
More information about the Python-list
mailing list