[Numpy-discussion] converting list of int16 values to bitmask and back to list of int32\float values

Nissim Derdiger NissimD at elspec-ltd.com
Thu Sep 14 13:11:20 EDT 2017

Hi all!
I'm writing a Modbus TCP client using pymodbus3 library.
When asking for some parameters, the response is always a list of int16.
In order to make the values usable, I need to transfer them into 32bit bites, than put them in the correct order (big\little endian wise), and then to cast them back to the desired format (usually int32 or float)
I've solved it with a pretty naïve code, but I'm guessing there must be a more elegant and fast way to solve it with NumPy.
Your help would be very much appreciated!

My code:
def Read(StartAddress, NumOfRegisters, FunctionCode,ParameterType,BitOrder):
                # select the Parameters format
                PrmFormat = 'f' # default is float
                if ParameterType == 'int':
                                PrmFormat = 'i'
                # select the endian state - maybe move to the connect function?
                endian = '<I'  # default is big endian
                if BitOrder == 'little':
                                endian = '>I'
                # start asking for the payload
                payload = None
                while payload == None:
                payload = Modbus.read_input_registers(StartAddress, NumOfRegisters)
                #### parse the answer
                ResultRegisters = []
                # convert the returned registers from list of int16 to list of 32 bits bitmaks
                for reg in range(int(NumOfRegisters / 2)):
                                ResultRegisters[reg] = struct.pack(endian, payload.registers[2 * reg]) + struct.pack(endian,payload.registers[2 * reg + 1])
                # convert this list to a list with the real parameter format
                for reg in range(len(ResultRegisters)):
                                ResultRegisters[reg]= struct.unpack(PrmFormat,ResultRegisters(reg))
                # return results
                return ResultRegisters
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20170914/45f19965/attachment.html>

More information about the NumPy-Discussion mailing list