16 字节的处理

字节的处理
  • 字符串
name = '中国联通'  # unicode
  • UTF-8 字节
name = '中国联通'
byte_data = name.encode('utf-8')  # byte  b'\xe4\xb8\xad\xe5\x9b\xbd\xe8\x81\x94\xe9\x80\x9a'
print(byte_data)
result = []
for item in byte_data:

    # 1 转换成十六进制 "0x12"
    hex_str = hex(item)

    # 2 去除0x
    # hex_2_str = hex_str.replace('0x', '')
    hex_2_str = hex_str[2:]  #切片
    # 3 不满2位,则前面补 0
    if len(hex_2_str) % 2 != 0:
        hex_2_str = hex_2_str.rjust(2, '0')
        result.append(hex_2_str)
    result.append(hex_2_str)
    # 4 将所有的十六制拼接起来字符串的形式
join_res = ''.join(result)
print(join_res)
  • 优化 v1
name = '中国联通'
byte_data = name.encode('utf-8')  # byte  b'\xe4\xb8\xad\xe5\x9b\xbd\xe8\x81\x94\xe9\x80\x9a'
print(byte_data)
result = []
for item in byte_data:
    # 1 转换成十六进制 "0x12"
    # 2 去除0x
    # 3 不满2位,则前面补 0
    result.append( hex(item)[2:].rjust(2, '0'))
# 4 将所有的十六制拼接起来字符串的形式
join_res = ''.join(result)
print(join_res)
  • 优化 v2 推导式
name = '中国联通'
result = ''.join([hex(item)[2:].rjust(2, '0') for item in name.encode('utf-8')])
    # 1 转换成十六进制 "0x12"
    # 2 去除0x
    # 3 不满2位,则前面补 0

# 4 将所有的十六制拼接起来字符串的形式

print(result)

posted @   jhchena  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示