如果我有
x = 123
,我想生成字节对象b'123'
.
我知道我可以用
str(x).encode('ascii')
或bytes(str(x), 'ascii')
完成这个。
我的问题是,是否可以在不必创建中间
str
对象的情况下执行此操作?
可以使用
%
格式:
encoded = b"%d" % x
我不确定这对于特定情况是否更有效。尽管我怀疑您是否也在进行其他格式设置,例如:
percentage = b"%d%%" % n
虽然下面的方法在性能方面是不可取的,但它实际上在没有任何中间字符串或隐式运行
str(123)
的情况下完成了工作。知道 ASCII 表中的偏移量后,我使用 int.to_bytes(...)
来创建字节。
import math
# function to extract the individual digits
def digit_enumerator(number):
# get number of digits to extract
n = int(math.log10(number))
while n >= 0:
# yield the digit
yield number // 10**n % 10
n -= 1
# the number to convert
x = 123
# numbers have an offset of 48 in ascii table
x_bytes = b''.join([(48+i).to_bytes(1, 'big') for i in digit_enumerator(x)])
print(x_bytes)
输出:
b'123'