Converting string into hex representation

谁都会走 提交于 2019-12-13 02:03:39

问题


I am looking for a good way to convert a string into a hex string.

For example:

  • '\x01\x25\x89' -> '0x012589'
  • '\x25\x01\x00\x89' -> '0x25010089'

Here is what I have come up with:

def to_hex(input_str):
    new_str = '0x'

    for char in input_str:
        new_str += '{:02X}'.format(ord(char))

    return new_str

It seems like there is probably a better way to do this that I haven't been able to find yet.


回答1:


You want the binascii module.

>>> binascii.hexlify('\x01\x25\x89')
'012589'
>>> binascii.hexlify('\x25\x01\x00\x89')
'25010089'



回答2:


Just encode to hex:

In [5]: s= "\x01\x25\x89"

In [6]: s.encode("hex")
Out[6]: '012589'

In [7]: s = "\x25\x01\x00\x89"
In [8]: s.encode("hex")
Out[8]: '25010089'


来源:https://stackoverflow.com/questions/34661563/converting-string-into-hex-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!