[英]converting large int list to byte string python
I need to convert int list into a byte string but I don't know how.我需要将 int 列表转换为字节字符串,但我不知道如何。 I can't use bytes()
because the values are too large.我不能使用bytes()
因为值太大。
bytes([152710136, 76354857, 38177353, 2252736081, 1126368238])
I get this error:我收到此错误:
ValueError: bytes must be in range(0, 256)
The expected value is:预期值为:
b'\xc4\xb7\x86\x17\xcd'
You can use .to_bytes
to return an array of bytes representing an integer.您可以使用.to_bytes
返回表示整数的字节数组。 Note : This works only in python 3.1 and above.注意:这仅适用于 python 3.1 及更高版本。
For example:例如:
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
I needed to use struct.unpack() and it accepts a byte string rather than a list of ints.我需要使用 struct.unpack() 并且它接受一个字节字符串而不是一个整数列表。 I was able to convert my list of ints to a byte string with:我能够将我的整数列表转换为字节字符串:
bytearray(mylist)
Tested on python 2.7.在 python 2.7 上测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.