""" Several functions for converting bytes to readable text or hex bytes. """ import struct from binascii import b2a_hex, a2b_hex def unhex(data): """ convert a possibly space separated list of 2-digit hex values to a byte-array """ if type(data) == bytes: data = data.decode("ascii") data = data.replace(" ", "") data = data.strip() return a2b_hex(data) def ashex(line): """ convert a byte-array to a space separated list of 2-digit hex values. """ return " ".join("%02x" % _ for _ in line) def aschr(b): """ convert a CP-1251 byte to a unicode character. This will make both cyrillic and latin text readable. """ if 32 <= b < 0x7F: return "%c" % b elif 0x80 <= b <= 0xFF: try: c = struct.pack("