简体   繁体   中英

Converting integer hex format into strings

I am programming an application to send data using UDP sockets with Python 3.1.

The command socket.send requires data in bytes format.

The problem I am having is that the package I have to send has three different fields, the first one contains a 16 bits integer variable ( c_ushort ) and so does the second field whereas the third one is an string whose length can go up to 900 characters.

I decided then to create an struct that contains these three fields:

class PHAL_msg(Structure):
    _fields_ = [("Port", c_ushort),
                ("Size", c_ushort),
                ("Text", c_wchar_p)]

I would expect I could send this object by just converting it to a bytes object:

Msg_TX = PHAL_msg(Port=PHAL_ADDRESS, Size=PAYLOAD_SIZE, Text='HELLO woRLD!')
socket.send(bytes(Msg_TX))

, but it does not work.

Any idea how this could be done?

Regards

You need to serialize your class, use pickle .

class Blah:
    def __init__(self,mynum, mystr):
        self.mynum = mynum
        self.mystr = mystr

a = Blah(3,"blahblah")
#bytes(a) # this will fail with "TypeError: 'Blah' object is not iterable"

import pickle
b = pickle.dumps(a) # turn it into a bytestring
c = pickle.loads(b) # and back to the class

print("a: ", a.__repr__(), a.mynum, a.mystr)
print("pickled....")
print("b: type is:",type(b)) # note it's already in bytes.
print(b.__repr__())
print("unpickled....")
print("c: ", c.__repr__(), c.mynum, c.mystr)

Output:

a:  <__main__.Blah object at 0x00BCB470> 3 blahblah
pickled....
b: type is: <class 'bytes'>
b'\x80\x03c__main__\nBlah\nq\x00)\x81q\x01}q\x02(X\x
05\x00\x00\x00mystrq\x03X\x08\x00\x00\x00blahblahq\x
04X\x05\x00\x00\x00mynumq\x05K\x03ub.'
unpickled....
c:  <__main__.Blah object at 0x00BCB950> 3 blahblah

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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