python 数字和字节互转

42 阅读1分钟

项目中可能会用到字节流通信,这时就需要用到以下两个方法了

def num_bytes(num:int, length:int):
    """ 数字转字节 \n
    num 数字 \n
    length 字节数 
    """
    arr = []
    for idx in range(length - 1, -1, -1):
        aa = (num >> (idx * 8)) & 0xff
        arr.append(aa.to_bytes(1))
    return b''.join(arr)

def bytes_num(bytes:bytes):
    """ 字节转数字 \n
    bytes 字节     
    """
    num = 0
    count = len(bytes)
    for idx in range(count - 1, -1, -1):
        num += bytes[count - idx - 1] << (idx * 8)
    return num

测试运行

print(num_bytes(65535, 4)) # 数字转字节
print(bytes_num(num_bytes(65535, 4))) # 字节转数字

运行结果

b'\x00\x00\xff\xff'
65535