Bytestring to normal chars。 python的struct.pack

时间:2017-03-19 21:40:19

标签: python scala struct.pack akka-io

我有这个生成字节的python代码

import threading
import socket
import struct
import time
from datetime import datetime
import random

TICKERS = ["AAPL", "GOOG", "MSFT", "SPY"]

timestamp = datetime.utcnow()
ticker = random.choice(TICKERS)
price = 90 + random.randrange(0, 400) * 0.05
size = random.randrange(100, 10000, 100)
msg = struct.pack("!QH%dsdI" % len(ticker), timestamp_millis(timestamp), len(ticker), ticker.encode("ascii"), price, size)
msg_len = struct.pack("!H", len(msg))
print("[%s:%d] %s: %s %.2f %d" % (host, port, timestamp, ticker, price, size))
client_socket.send(msg_len + msg)

我正在侦听使用akka io生成此数据的端口。我得到这样的数据:

client received some data: ByteString(0, 26, 0, 0, 1, 90, -30, -44, -92, 21, 0, 4, 71, 79, 79, 71, 64, 88, -106, 102, 102, 102, 102, 102, 0, 0, 10, -116)
client received some data: ByteString(0, 26, 0, 0, 1, 90, -30, -44, -86, -75, 0, 4, 77, 83, 70, 84, 64, 88, -26, 102, 102, 102, 102, 102, 0, 0, 8, -104)
client received some data: ByteString(0, 26, 0, 0, 1, 90, -30, -44, -79, -59, 0, 4, 71, 79, 79, 71, 64, 87, 86, 102, 102, 102, 102, 102, 0, 0, 33, -4)
client received some data: ByteString(0, 25, 0, 0, 1, 90, -30, -44, -69, -126, 0, 3, 83, 80, 89, 64, 88, -29, 51, 51, 51, 51, 51, 0, 0, 0, -56)

我有几个问题: 1.如何将这些字节解码为普通字符?我试试:

scala> val bs = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)
bs: akka.util.ByteString = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)
scala> bs.utf8String
res3: String = ?????Z��?�??AAPL@X�????????,

2。什么是!QH%dsdI? struct.pack如何工作?我不知道python

1 个答案:

答案 0 :(得分:0)

您可以使用名为 decodeString 的方法:

scala> val bs = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)
bs: akka.util.ByteString = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)

scala> bs.decodeString("US-ASCII")

!QH%dsdI 是格式字符串,它是从格式字符构建的,用于指定打包/解包的数据类型。

您可以参考this link参考struct.pack

请注意,参数必须与完全格式所需的值匹配。