0

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.