|
|
|
import struct
|
|
|
|
|
|
|
|
def reorderBytes(byteStream, format):
|
|
|
|
if format == 'ABCD':
|
|
|
|
return byteStream
|
|
|
|
elif format == 'DCBA':
|
|
|
|
return byteStream[::-1]
|
|
|
|
elif format == 'BADC':
|
|
|
|
return bytes([byteStream[1], byteStream[0], byteStream[3], byteStream[2]])
|
|
|
|
elif format == 'CDAB':
|
|
|
|
return bytes([byteStream[2], byteStream[3], byteStream[0], byteStream[1]])
|
|
|
|
else:
|
|
|
|
raise ValueError("Invalid format")
|
|
|
|
|
|
|
|
# 大端模式
|
|
|
|
def floatToABCD(value):
|
|
|
|
valueByte = struct.unpack('>HH',struct.pack('>f', value))
|
|
|
|
return valueByte
|
|
|
|
|
|
|
|
# 小端模式
|
|
|
|
def floatToDCBA(value):
|
|
|
|
valueByte = struct.unpack('>HH', struct.pack('<f', value))
|
|
|
|
return valueByte
|
|
|
|
|
|
|
|
# 单字反转
|
|
|
|
def floatToBADC(value):
|
|
|
|
valueByte = struct.unpack('<HH', struct.pack('>f', value))
|
|
|
|
return valueByte
|
|
|
|
|
|
|
|
# 双字反转
|
|
|
|
def floatToCDAB(value):
|
|
|
|
valueByte = struct.unpack('<HH', struct.pack('<f', value))
|
|
|
|
return valueByte
|
|
|
|
|
|
|
|
|
|
|
|
def ABCDToFloat(value):
|
|
|
|
valueByte = struct.unpack('>f',struct.pack('>HH', value[0], value[1]))
|
|
|
|
return valueByte[0]
|
|
|
|
|
|
|
|
# 小端模式
|
|
|
|
def DCBAToFloat(value):
|
|
|
|
valueByte = struct.unpack('<f', struct.pack('>HH', value[0], value[1]))
|
|
|
|
return valueByte[0]
|
|
|
|
|
|
|
|
def BADCToFloat(value):
|
|
|
|
valueByte = struct.unpack('>f', struct.pack('<HH', value[0], value[1]))
|
|
|
|
return valueByte[0]
|
|
|
|
|
|
|
|
|
|
|
|
def CDABToFloat(value):
|
|
|
|
valueByte = struct.unpack('<f', struct.pack('<HH', value[0], value[1]))
|
|
|
|
return valueByte[0]
|
|
|
|
|
|
|
|
def floatToBytes(values, length, order):
|
|
|
|
# 判断order是否为ABCD或BADC
|
|
|
|
# order = '>' if order in ['ABCD', 'BADC'] else '<'
|
|
|
|
# hOrder = '<'if order.byte in ['ABCD', 'DCBA'] else '>'
|
|
|
|
# 获取values的长度
|
|
|
|
valuesNums = len(values)
|
|
|
|
# 将values转换为字节流
|
|
|
|
valueByte = struct.pack(f"!{'f' * valuesNums}", *values)
|
|
|
|
valueByte = reorderBytes(valueByte, format = order)
|
|
|
|
print(ABCDToFloat(struct.unpack('!HH', valueByte)))
|
|
|
|
# {'B' * (length - 4 * valuesNums) *[0] * (length - 4 * valuesNums)
|
|
|
|
# 返回转换后的字节流
|
|
|
|
# return valueByte
|
|
|
|
|
|
|
|
def coilsToBytes(values, length):
|
|
|
|
decimalNumbers = []
|
|
|
|
binaryNumber = ''.join([str(x) for x in list(reversed(values))])
|
|
|
|
zeroNeeded = 0 if len(binaryNumber) % 8 == 0 else 8 - (len(binaryNumber) % 8)
|
|
|
|
binaryNumber = '0' * zeroNeeded + binaryNumber
|
|
|
|
for i in range(0, len(binaryNumber), 8):
|
|
|
|
eightValues = binaryNumber[i:i+8]
|
|
|
|
decimalNumbers.append(int(eightValues, 2))
|
|
|
|
valueByte = struct.pack("B" * length, *decimalNumbers, *[0] * (length - len(decimalNumbers)))
|
|
|
|
return valueByte
|
|
|
|
|
|
|
|
# print(coilsToBytes([1] * 2, 3))
|
|
|
|
floatToBytes([3.14], 5, 'ABCD')
|
|
|
|
|
|
|
|
|