signed vs unsigned int

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Wed Jun 2 03:03:27 EDT 2010


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



More information about the Python-list mailing list