栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

导读
     最近工作上碰到了一个将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'xe6x88x91xe6x98xafxe4xb8xadxe5x9bxbdxe4xbaxba', b'xe6x97x97xe8x88xb0']
res = hex2ch(hex_bytes)
print("解码之后的数据为:", res)

# 参数为单个16进制字符串
hex_bytes = b'xe6x97x97xe8x88xb0'
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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/757789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号