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

2024-05-08 20:25:16 发布

您现在位置: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()

我得到客户的回复

^{pr2}$

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

需要解析头文件。在

<$$><L><ID><command><data><checksum><\r\n>
  • 头=2字节,它将以0x24的十六进制代码表示
  • L=2字节,十六进制码格式。在
  • ID=7字节,十六进制码格式。在
  • 命令=2字节,它将是十六进制代码
  • 数据将采用ascii格式。在
  • 校验和=2字节,采用十六进制代码

提前谢谢。在


Tags: 代码fromimportself字节factorydef格式
2条回答

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

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)

另一个答案是指向struct的链接

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

阅读有关structhere的更多信息。在

相关问题 更多 >