signed vs unsigned int

Discussion in 'Python' started by johnty, Jun 2, 2010.

  1. johnty

    johnty Guest

    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). however, what i'd like is to get the _signed_
    integer value. whats the easiest way to do this?

    thanks in advance.

    johnty
     
    johnty, Jun 2, 2010
    #1
    1. Advertisements

  2. johnty, 02.06.2010 08:43:


    See the struct module, it supports various different C types.

    Stefan
     
    Stefan Behnel, Jun 2, 2010
    #2
    1. Advertisements

  3. An array or a list?


    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 D'Aprano, Jun 2, 2010
    #3
  4. johnty

    johnty Guest



    the struct docs is exactly what i needed to read. "unpacking" it as a
    signed char did the trick. thanks guys!
     
    johnty, Jun 2, 2010
    #4
  5. johnty

    John Machin Guest



    signed = unsigned if unsigned <= 127 else unsigned - 256
     
    John Machin, Jun 2, 2010
    #5


  6. 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
     
    Patrick Maupin, Jun 4, 2010
    #6
  7. johnty

    John Nagle Guest

    Try reading into a type "bytearray". That's the proper data type
    for raw bytes.

    John Nagle
     
    John Nagle, Jun 4, 2010
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.