简体   繁体   中英

Convert hex string to characters in python3

I need to convert a string such as 5555555547aa into a string of characters (that one would be �GUUUU ). I have a function working in python2 which is posted below, but I can't get anything to work right in python3. How would I do this?

    def hex_conv(hex_str):
      arr = [hex_str[i:i+2] for i in range(0, len(hex_str), 2)]
      rev = arr[::-1]
      out_str = ""
      for i in rev:
        print(i)
        out_str += ("\\x" + i).decode("string_escape")
      return out_str

More Clearly of what I need outputted (in Python2):

print('\xaa\x47\x55\x55\x55\x55')

I have tried

print(bytes.fromhex("5555555547aa")[::-1].decode("utf-8", errors="replace"))

which doesn't quite work. It appears to produce the same output but the actual bytes are different.

Note: The output of this is going to be piped into another program (for binary exploitation) so the bytes need to be printed exact.

You just need to combine 2 steps: convert from hex to a bytestring with bytes.fromhex , and to print a bytestring to stdout using sys.stdout.buffer.write . Putting it all together:

import sys
sys.stdout.buffer.write(bytes.fromhex("5555555547aa")[::-1])

Sourced from hexadecimal string to byte array in python and How to write a raw hex byte to stdout in Python 3?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM