gpt4 book ai didi

python - 如何解决TypeError : 'str' does not support the buffer interface?

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:45 24 4
gpt4 key购买 nike

我的代码:

big_int = 536870912
f = open('sample.txt', 'wb')

for item in range(0, 10):
y = bytearray.fromhex('{:0192x}'.format(big_int))
f.write("%s" %y)
f.close()

我想将 long int 转换为字节。但是我得到了 TypeError: 'str' does not support the buffer interface

最佳答案

除了@Will回答,最好用with声明打开你的文件。此外,如果您使用 python 3.2 及更高版本,则可以使用 int.to_bytesint.from_bytes逆转这个过程。

我说的例子:

big_int=536870912

with open('sample.txt', 'wb') as f:
y = big_int.to_bytes((big_int.bit_length() // 8) + 1, byteorder='big')
f.write(y)
print(int.from_bytes(y, byteorder='big'))

最后的print是告诉你如何反转它。

关于python - 如何解决TypeError : 'str' does not support the buffer interface?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com