From: John Machin on 2 Jun 2010 07:25 On Jun 2, 4:43 pm, johnty <johntyw...(a)gmail.com> wrote: > i'm reading bytes from a serial port, and storing it into an array. > > each byte represents a signed 8-bit int. > > currently, the code i'm looking at converts them to an unsigned int by > doing ord(array[i]). however, what i'd like is to get the _signed_ > integer value. whats the easiest way to do this? signed = unsigned if unsigned <= 127 else unsigned - 256
From: Patrick Maupin on 4 Jun 2010 15:48 On Jun 2, 6:25 am, John Machin <sjmac...(a)lexicon.net> wrote: > On Jun 2, 4:43 pm, johnty <johntyw...(a)gmail.com> wrote: > > > i'm reading bytes from a serial port, and storing it into an array. > > > each byte represents a signed 8-bit int. > > > currently, the code i'm looking at converts them to an unsigned int by > > doing ord(array[i]). however, what i'd like is to get the _signed_ > > integer value. whats the easiest way to do this? > > signed = unsigned if unsigned <= 127 else unsigned - 256 That works, but I prefer not using if/else for things that can be described in an expression without it. Other ways of expressing this include: signed = (unsigned & 127) - (unsigned & 128) signed = (unsigned & 127) * 2 - unsigned signed - unsigned - 2 * (unsigned & 128) Regards, Pat
From: John Nagle on 4 Jun 2010 16:26 johnty wrote: > i'm reading bytes from a serial port, and storing it into an array. Try reading into a type "bytearray". That's the proper data type for raw bytes. John Nagle
First
|
Prev
|
Pages: 1 2 Prev: plac, the easiest command line arguments parser in the world Next: Python Forum |