Rambo partyush
Rambo partyush

Reputation: 83

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). In total 24 bytes, 8 bytes for header info, 8 bytes for the double data. When I run the following code in Python 3 using UDP socket:

'''

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:

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. Now I can see some ascii characters "?" 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?" i.e. "xf0 x3f" is actually double "1". Please help. I am getting the following data in Wireshark

Data: 0100647802001000000000000000f03f000000000000f03f

Kindly help me.

Upvotes: 1

Views: 1572

Answers (2)

zariiii9003
zariiii9003

Reputation: 356

Use struct to convert to numeric:

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,)

Upvotes: 0

remram
remram

Reputation: 5203

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,)

Upvotes: 3

Related Questions