如何在 Python 中将字节串转换为数值?

问题描述 投票:0回答:1

我从opcua服务器端的ExtensionObject节点读取到的字节串是如何将其转换为十进制,这是根据python中的struct模块解析其中一个字节串的结果。 这显然是错误的,我该怎么办,我得到的数据是这样的 这是我的代码:

import struct
# Example byte string containing double values
byte_string = b'\x84^\x05\x00\x00\xf7\n\x19\n\....'
# Determine the size of a double in bytes
double_size = struct.calcsize('!d')

# Calculate the number of double values in the byte string
num_values = len(byte_string) // double_size

# Loop through the byte string and unpack double values
for i in range(num_values):
    # Calculate the offset for the current double value
    offset = i * double_size
    # Unpack the double value from the byte string
    double_value = struct.unpack_from('!d', byte_string, offset)[0]
    print(double_value)

如果有人有建议,请提前谢谢。

python opc-ua
1个回答
0
投票

正如 @ivvija 评论的那样,如果您预先知道数据的二进制结构,则可以编写代码来解码扩展对象。要找出结构,请使用 OPC UA 客户端(例如 UaExpert),并读取您正在读取值/订阅值的节点的 DataTypeDefinition 属性。

通用解决方案,即如果您有多种数据类型,或者预先未知数据类型,则使用可以解释 DataTypeDefinition(或数据类型字典 - OPC UA 中的较旧方法)的 OPC UA 客户端库,并且已经给你解码的数据了。示例如下:https://github.com/OPCLabs/Examples-QuickOPC-Python/blob/main/CPython/Console/UADocExamples/ComplexData/Net._GenericData.DataTypeKind1.Main1.py .

© www.soinside.com 2019 - 2024. All rights reserved.