dkakoti dkakoti - 1 year ago 68
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):

class ChatFactory(Factory):

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

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


I got response from the client with


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.


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

  • 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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download