From: johnty on 2 Jun 2010 02:43 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? thanks in advance. johnty From: Stefan Behnel on 2 Jun 2010 03:01 johnty, 02.06.2010 08:43:> 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? See the struct module, it supports various different C types. Stefan From: Steven D'Aprano on 2 Jun 2010 03:03 On Tue, 01 Jun 2010 23:43:33 -0700, johnty wrote: > i'm reading bytes from a serial port, and storing it into an array. An array or a list? > 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? >>> import array >>> s = 'Some unsigned bytes \xc3\x80\xc3\xa0\xc3\xa6\xc3\x9f\xc2\xb5' >>> array.array('b', s) array('b', [83, 111, 109, 101, 32, 117, 110, 115, 105, 103, 110, 101, 100, 32, 98, 121, 116, 101, 115, 32, -61, -128, -61, -96, -61, -90, -61, -97, -62, -75]) See also the fromstring method of array objects. -- Steven From: Christian Heimes on 2 Jun 2010 03:04 > 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? http://docs.python.org/library/struct.html From: johnty on 2 Jun 2010 03:32 On Jun 2, 12:04 am, Christian Heimes 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? > > http://docs.python.org/library/struct.html the struct docs is exactly what i needed to read. "unpacking" it as a signed char did the trick. thanks guys!  |  Next  |  Last Pages: 1 2 Prev: plac, the easiest command line arguments parser in the worldNext: Python Forum