将int和bytearray转换为Python struct的ByteString Socket
我需要通过一个套接字(socket)向服务器发送一个整数和一个字节数组(大小为200)。但是,socket.send()这个函数只接受一个字符串,所以我需要把整数和字节数组都转换成字节,然后合成一个字符串。我试着用struct.pack()把它们都转换成字符串,整数转换得很好,但字节数组就不行。
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
print "Connected to: ", s.getpeername()
#Trying to put int and bytearray into 1 string
a= 02 # int
b= bytearray(200) #bytearray
c = struct.pack("B", a)
c += b
s.send(c)
print s.recv(1024)
1 个回答
0
把它们连接起来:
>>> import struct
>>> struct.pack('<l', 1234) + bytearray([0]*10)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
或者也可以指定字节数组:
>>> struct.pack('<l10s', 1234, bytearray([0]*10)) # In Python 3.x
# struct.pack('<l10s', 1234, bytes(bytearray([0]*10))) # In Python 2.x
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'