汉字与十六进制的相互转化

导读

     最近工作上碰到了一个将16进制串转成汉子的需求,网上查了下,发现有些网页版本的,但离线使用的没有那种可以直接调用的函数,所以这里整理了一下,将转换功能写成一个完整的函数,哪里需要,复制粘贴过去就可以用。

16进制转汉字

函数定义:

def hex2ch(hex_bytes):
    """
    :param hex_bytes: 接受的参数可以是16进制的bytes列表,也可以是单个16进制bytes
    :return:  返回的结果跟传入的类型一致
    """
    if not isinstance(hex_bytes, list) and not isinstance(hex_bytes, bytes):
        raise ValueError("hex type error, need list or type")
    is_list = True
    if isinstance(hex_bytes, bytes):
        is_list = False
        hex_bytes = [hex_bytes]
    result = []
    for hex_byte in hex_bytes:
        result_byte = hex_byte.decode('utf-8')
        result.append(result_byte)
    return result if is_list else result[0]

使用demo:

# 参数为列表
hex_bytes = [b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba', b'\xe6\x97\x97\xe8\x88\xb0']
res = hex2ch(hex_bytes)
print("解码之后的数据为:", res)

# 参数为单个16进制字符串
hex_bytes = b'\xe6\x97\x97\xe8\x88\xb0'
res = hex2ch(hex_bytes)
print("解码之后的数据为:", res)

汉字转16进制

def ch2hex(chs, return_hex=True):
    if not isinstance(chs, list) and not isinstance(chs, str):
        raise ValueError("chs type error, need list or str")
    is_list = True
    if isinstance(chs, str):
        is_list = False
        chs = [chs]
    result = []
    for ch in chs:
        hex_ch = ch.encode('utf-8')
        if return_hex:
            hex_ch = hex_ch.hex()
        result.append(hex_ch)
    return result if is_list else result[0]

使用demo:

# 字符串作为输入
chinese = "我是中国人"
res = ch2hex(chinese, return_hex=True)
print("编码之后的数据为:", res)

# 字符串列表输入
chinese = ["我是中国人", "旗舰店"]
res = ch2hex(chinese, return_hex=False)
print("编码之后的数据为:", res)

参考文献:
https://docs.python.org/3/
https://blog.csdn.net/weixin_47513022/article/details/121627252

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值