简体   繁体   English

接收到的 UDP 字节混合了 hex 和 ascii; 如何解码?

[英]UDP bytes received with hex and ascii mixed; How to decode?

I am running a UDP client in a real-time simulation (OPAL RT), it is basically sending two doubles (1 and 1) and I am receiving the values with some timestamps and header information (I guess).我在实时模拟(OPAL RT)中运行 UDP 客户端,它基本上发送两个双精度值(1 和 1),我收到带有一些时间戳和 header 信息的值(我猜)。 In total 24 bytes, 8 bytes for header info, 8 bytes for the double data.总共 24 个字节,8 个字节用于 header 信息,8 个字节用于双数据。 When I run the following code in Python 3 using UDP socket:当我使用 UDP 套接字在 Python 3 中运行以下代码时:

''' '''

import socket

UDP_IP = "10.10.114.22"
UDP_PORT = 25000

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
print("socket bound, waiting for data...")

while True:

    raw = sock.recv(1024)
    print(raw,len(raw),type(raw))

''' I get the following output: ''' 我得到以下 output:

b'\x01\x00\xecV\x02\x00\x10\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?'

which is a 24 byte string.这是一个 24 字节的字符串。 Now I can see some ascii characters "?"现在我可以看到一些 ascii 字符“?” with the hex data.与十六进制数据。 How do I decode this?我该如何解码? I think out of the 64 bits for each data byte 1 bit is the sign, 11 exponents and 52 mantissa, but I cannot grasp how "xf0?"我认为每个数据字节的 64 位中有 1 位是符号,11 个指数和 52 个尾数,但我无法理解“xf0?” ie "xf0 x3f" is actually double "1".即“xf0 x3f”实际上是双“1”。 Please help.请帮忙。 I am getting the following data in Wireshark我在 Wireshark 中获得以下数据

Data: 0100647802001000000000000000f03f000000000000f03f

Kindly help me.请帮助我。

You can use the struct module:您可以使用结构模块:

>>> raw = b'\x01\x00\xecV\x02\x00\x10\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?'
>>> struct.unpack('d', raw[8:16])
(1.0,)
>>> struct.unpack('d', raw[16:24])
(1.0,)

Use struct to convert to numeric:使用 struct 转换为数字:

import struct

s = b'\x01\x00\xecV\x02\x00\x10\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?'


ba = bytearray(s)

print(struct.unpack('<d', ba[-16:-8]))
print(struct.unpack('<d', ba[-8:]))

>>> (1.0,)
    (1.0,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM