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 bytestring
1个回答
0
投票

尝试这样:

import struct


byte_string = b'\x84^\x05\x00\x00\xf7\n\x19\n...'
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
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]
    double_values.append(double_value)

print("Double Values:", double_values)
© www.soinside.com 2019 - 2024. All rights reserved.