Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uchar to ushort in python

My title might seem strange since there are no such things as uchar and ushort in Python so let me explain : I get a list of 8 bits data from a bulk transfer but I need these in 16 bits. Hence I do this :

frame = dev.read(0x82, packetLength, interface, timeout) # bulk transfer
if len(frame) == packetLength
    for i in range(0, packetLength, 2):
        newFrame.append(frame[i+1]*256 + frame[i])

So yes it works but it is extremely slow and I need to run it on a Raspberry Pi...

Does anyone of you know a better way to do the same thing?

like image 226
Ben Avatar asked Jun 06 '26 01:06

Ben


1 Answers

Using struct, the solution would be:

import struct

frame = dev.read( ... )

fmt = "<%dH" % (len(frame) / 2)
newFrame = struct.unpack(fmt, frame)

Explanation of fmt string:

  • < - Data is in little-endian format
  • %d - The size of your array (it modifies the following format specifier)
  • H - Format specifier Interpret the data as ushorts
like image 195
memoselyk Avatar answered Jun 07 '26 16:06

memoselyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!