dkakoti dkakoti - 5 months ago 15
Python Question

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.
What is the best way to convert this data into human readable format?

I need to parse header, L and ID.

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



  • header = 2 bytes and it will be in hex code representation of
    0x24

  • L = 2 bytes and it is in the format of hex code .

  • ID = 7 bytes and it is in the format of hex code .

  • command = 2 bytes, it will be in hex code

  • data will be in ascii format.

  • checksum = 2 bytes and in hex code



Thanks in advance.

Answer

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

Comments