interpreting bytes as ushorts in Python
Question: I need to interpret 16 bytes received over a TCP socket as 8 ushorts.

This line correctly receives the data (the 16-bit values of 8 a-d converters),
and I can access each byte as an index into a byte array:

    
    
    vals = bytearray(s.recv(16))
    

And I could create 8 variables and decode each:

    
    
    ad1 = (ord(vals[0]) * 256)+ord(vals[1])
    

But it would be more elegant if I could recast this array as 8 ushorts.

I have tried many variations of struct.unpack, with just as many syntax
errors. My background is in C, so I would ordinarily use a union or recast a
byte pointer, but...

can anyone point me in the right direction? thanks, and my apologies if this
has been asked before.

#

here is the full monty:

    
    
    import socket,struct,time
    import xrlib
    
    def readADx(socket,a2dnumber):
    # a2dnumber 1 - 8
    if a2dnumber < 1 or a2dnumber > 8:
          return 0
    a2d = a2dnumber + 0x9D
    tdata = struct.pack('BB',0xFE,a2d)
    s.send(tdata)
    val = ord(s.recv(1)) * 256
    val = val + ord(s.recv(1))
    return val
    #
    # define TCP client socket:
    # 
    IPADDR = '192.168.99.9'
    PORTNUM = 2101
    s =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((IPADDR,PORTNUM))
    tdata = struct.pack('BB',0xFE,0xA7)
    s.send(tdata)
    #
    # the problem:
    #
    vals = bytearray(s.recv(16))
    adv = struct.unpack('8H',vals)
    #
    # get the true values for A/D 7 and 8:
    #
    ad8 = readADx(s,8);
    ad7 = readADx(s,7);
    s.close()
    
    print("%04X %04X %04X %04X %04X %04X %04X %04X"%adv[0],adv[1],adv[2],adv[3],adv[4],adv[5],adv[6],adv[7]))
    print("AD8: %d"%(ad8));
    print("AD7: %d"%(ad7));
    print("adv[7]: %d"%(adv[7]));
    print("adv[6]: %d"%(adv[6]));
    

running this gives this error:

    
    
     struct.error: unpack requires a string argument of length 16
    

this is the error I would invariably get, with different argument lengths.

this code works:

    
    
     adv = struct.unpack('8H',s.recv(16))
    

but the byte order of each reading (adv[x]) is reversed. I found
socket.ntohs() to fix this.

Still not sure why the struct.unpack would not work with the bytearray arg...


Answer: (transforming a comment to an answer)

    
    
    ad1 = struct.unpack('8H', vals)
    

