将字符串转换为十六进制表示 [英] Converting string into hex representation

查看:87
本文介绍了将字符串转换为十六进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将字符串转换为十六进制字符串的好方法.

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

例如:

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

这是我想出的:

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.

推荐答案

您需要 binascii 模块.

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

这篇关于将字符串转换为十六进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆