如何将二进制和 ascii 的组合转换为 python 中的人类可读格式

How to convert combination of binary and ascii to human readable format in python

下面是我通过套接字接收数据的代码。

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):

    def lineReceived(self, line):
        print(line)

class ChatFactory(Factory):

   def __init__(self):
       self.users = {} # maps user names to Chat instances

   def buildProtocol(self, addr):
       return Chat()

reactor.listenTCP(9600,ChatFactory())
reactor.run()

我收到客户的回复

b'$$\x00pP$\x91\x97\x01\xff\xff\x99\x99P000002.000,V,0000.0000,N,00000.0000,E,0.00,000.00,060180,,*09|||0000|0000,0000|000000113|00000[\x86'

是十六进制码和ascii的组合,位置信息是ascii格式。 将此数据转换为人类可读格式的最佳方法是什么?

我需要解析 header、L 和 ID

<$$><L><ID><command><data><checksum><\r\n>

提前致谢。

你可以使用struct.unpack(),但是你必须知道你要解压的是什么(int,long,signed,等等),如果它被编码超过1个字节,ASCII是7个位,编码为 1 个字节。

详细了解结构 here

这可以用二进制字符串解决:

import struct
header = line[:2]
if header!=b'$$':
    raise RuntimeError('Wrong header')
# Assumes you want two have 2 bytes, not one word
L = struct.unpack('BB',line[2:4])
ID = struct.unpack('7B', line[4:11])
location = line[11:]
print 'L={},{}, ID={}, location={}'.format(L[1],L[2], ''.join(str(b) for b in ID, location)

要构造的 link 在另一个答案中