📌  相关文章
📜  如何在不编码 python 代码示例的情况下将字符串转换为字节

📅  最后修改于: 2022-03-11 14:45:52.264000             🧑  作者: Mango

代码示例2
import struct

def rawbytes(s):
    """Convert a string to raw bytes without encoding"""
    outlist = []
    for cp in s:
        num = ord(cp)
        if num < 255:
            outlist.append(struct.pack('B', num))
        elif num < 65535:
            outlist.append(struct.pack('>H', num))
        else:
            b = (num & 0xFF0000) >> 16
            H = num & 0xFFFF
            outlist.append(struct.pack('>bH', b, H))
    return b''.join(outlist)