我有一个非负的int,我想有效地将它转换为包含相同数据的big-endian字符串.例如,int 1245427(0x1300F3)应该生成一个长度为3的字符串,其中包含三个字符,其字节值为0x13,0x00和0xf3.
我的整数是35(基数为10)的数字.
我该怎么做呢?
在Python 3中,可以格式化一个字符串,如:
"{0}, {1}, {2}".format(1, 2, 3)
但是如何格式化字节?
b"{0}, {1}, {2}".format(1, 2, 3)
加油AttributeError: 'bytes' object has no attribute 'format'.
如果没有format字节方法,如何格式化或"重写"字节?
在Python 2中,要获得字符串中十六进制数字的字符串表示,您可以这样做
>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'
在Python 3中,它不再起作用(在Python 3.2和3.3上测试):
>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex
这里至少有一个答案提到hex在Python 3中已经删除了编解码器.但是,根据文档,它在Python 3.2中被重新引入,作为"字节到字节映射".
但是,我不知道如何使这些"字节到字节映射"工作:
>>> b'\x12'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
而且文档也没有提到(至少不是我看的地方).我一定错过了一些简单的东西,但我看不出它是什么.
我认为这是一个 python 新手问题,但是如何将单个字节(在本例中为零)写入文件?
我有这个代码:
f = open("data.dat", "wb")
f.write(0)
f.close()
但在写入行上出现错误:
类型错误:需要类似字节的对象,而不是“int”
我想我需要用字节文字替换 0,但无法弄清楚语法。我所有的搜索都告诉我有关将字符串转换为字节的信息。我尝试过0B,但没有成功。
我正在创建一个将大型 numpy 数组存储在pyarrow.plasma. 我想给每个数组一个唯一的、确定性的 plasma.ObjectID,np.array遗憾的是不可散列我当前的(损坏的)方法是:
import numpy as np
from pyarrow import plasma
def int_to_bytes(x: int) -> bytes:
    return x.to_bytes(
        (x.bit_length() + 7) // 8, "big"
    )  # /sf/ask/1471238891/
def get_object_id(arr):
    arr_id = int(arr.sum() / (arr.shape[0]))
    oid: bytes = int_to_bytes(arr_id).zfill(20)  # fill from left with zeroes, must be of length 20
    return plasma.ObjectID(oid)
但这很容易失败,例如:
arr = np.arange(12)
a1 = arr.reshape(3, 4)
a2 = arr.reshape(3,2,2)
assert get_object_id(a1) != get_object_id(a2), 'Hash collision'
# another good test case …