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

不问归期 提交于 2020-04-08 17:54:04

最近在搞一个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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!