python 字符串、数字转换为bytes和bytes转换为字符串

最近在搞一个socket,用python向C#服务器发送bytes和从服务器接收bytes,搞了一天基本弄清楚了这些转换关系。

建立一个空的bytes数组:

a=bytes(5)
print(a)

  执行结果:

b'\x00\x00\x00\x00\x00'

 将int转化为bytes(大端字节序):

def intToBytes(value, length):
    result = []
    for i in range(0, length):
        result.append(value >> (i * 8) & 0xff)
    result.reverse()
    result_bytes=bytes(result)
    return result_bytes

print(intToBytes(-95,3))

  执行结果:

b'\xff\xff\xa1'下

下班了,后面补哈

将字符串转为bytes:

posted @ 2019-09-12 16:52  志不坚者智不达  阅读(5339)  评论(4编辑  收藏  举报