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 @ 2024-09-25 22:51  jhchena  阅读(24)  评论(0)    收藏  举报