Home > Software design >  ASCII decoding using Python
ASCII decoding using Python

Time:02-04

I am using Python 2.7 (due to toolchains dependency :-( )

Input String = 'F1 88 52 45 4D 41 2D 33 43 37 38 32 2D 42 42 00 00 00 00 00 00 00 00 00'

Output String = REMA-3C782-BB

Please help me in decoding the ASCII string(in hex) to the Output String as above.

This below code throws error:

BResponse = 'F1 88 52 45 4D 41 2D 33 43 37 38 32 2D 42 42 00 00 00 00 00 00 00 00 00'                      
BResponse = BResponse.decode('ASCII')

CodePudding user response:

It looks like you're discarding non-ascii characters, you can use string.printable in order to look for characters you don't want in your output.

import string

def parse_response(response):
    return ''.join([chr(int(hex_letter, 16))
                    if chr(int(hex_letter, 16)) in string.printable
                    else ''
                    for hex_letter in response.split(' ')])

Making it return what we intended:

BResponse = 'F1 88 52 45 4D 41 2D 33 43 37 38 32 2D 42 42 00 00 00 00 00 00 00 00 00'
print parse_response(BResponse)
REMA-3C782-BB

CodePudding user response:

I would do it following way

cipher = '52 45 4D 41'  # this should give REMA
plain = ''.join(['%c' % int(i,16) for i in cipher.split()])
print plain

gives output

REMA

(tested in Python 2.7.18)

  • Related