[英]How to convert combination of binary and ascii to human readable format in python
Below is my code for receiving data over socket. 下面是我通过套接字接收数据的代码。
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()
I got response from the client with 我得到了客户的回应
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'
which is combination of hex code and ascii, the location information is in ascii format. 它是十六进制代码和ascii的组合,位置信息采用ascii格式。 What is the best way to convert this data into human readable format?
将这些数据转换为可读格式的最佳方法是什么?
I need to parse header, L and ID . 我需要解析标头L和ID 。
<$$><L><ID><command><data><checksum><\r\n>
0x24
0x24
十六进制代码表示 Thanks in advance. 提前致谢。
This can be solved just with the binary string: 只需使用二进制字符串即可解决:
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)
The link to struct is in the other answer struct的链接在另一个答案中
You can use struct.unpack()
, but you have to know what you are gonna unpack (int, long, signed, etc.), the endiness if it is encoded on more that 1 bytes, ASCII are 7 bits, encoded on 1 byte. 您可以使用
struct.unpack()
,但是您必须知道要解压缩的内容(int,long,signed等),如果编码超过1个字节,ASCII编码为7位,编码为1个,则表示结束符字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.