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:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM