Reputation: 1638
I receive a bunch of binary data and I want it be become a readable string again.
# Get data length in bits
dataLen = headerLen + (payLoadLen * 8) - bytes.pos
if dataLen > 0:
eventData = []
for i in range(dataLen / 8):
eventData.append(bytes.read(8).int)
m.setEventData(eventData)
logging.debug("[D] Event data: %s" % eventData)
which results in a log like:
[D] Event data: [87, 84, 94, 87, 44, 36, 70, 77, 83, 52, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 13, 10, 87, 84, 94, 87, 44, 36, 70, 77, 83, 49, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 44, 48, 13, 10]
If you look http://www.asciitable.com/, I know it's correct. The first characters are indeed WT^W,FMS...
How can I change this code so that the logging has a more human readable string?
Upvotes: 0
Views: 119
Reputation: 10361
To decode the characters, you will want to use the chr builtin. To join them together, you will want to use the join function from the string library.
# Get data length in bits
dataLen = headerLen + (payLoadLen * 8) - bytes.pos
if dataLen > 0:
eventData = []
for i in range(dataLen / 8):
eventData.append(bytes.read(8).int)
m.setEventData(eventData)
c = []
for p in eventData:
c.append(chr(p))
out = "".join(c)
logging.debug("[D] Event data pre: %s" % eventData)
logging.debug("[D] Event data post: %s" % out)
Upvotes: 1
Reputation: 25072
You need to convert the codes into string characters and then join the characters together:
myString = ''.join(map(chr, eventData))
If you have a hard time understanding what the code above does look at the code below - it's quite similar. Both versions use chr()
to convert every numerical ASCI code to one-character string and then join the strings together. The only difference is, in the former version I replaced map()
with a simple for loop.
characters = []
for code in eventData:
characters.append(chr(code))
myString = ''.join(characters)
Upvotes: 1