转换为二进制并保留前导零 [英] Convert to binary and keep leading zeros
问题描述
我正在尝试使用 Python 中的 bin() 函数将整数转换为二进制.但是,它总是删除我实际需要的前导零,因此结果始终为 8 位:
示例:
bin(1) ->0b1# 我想要什么:bin(1) ->0b00000001
有没有办法做到这一点?
使用 format()
函数:
format()
函数只是按照 格式规范迷你语言.#
使格式包含 0b
前缀,010
大小将输出格式化为适合 10 个字符的宽度,0
填充;0b
前缀 2 个字符,二进制数字 8 个字符.
这是最紧凑、最直接的选择.
如果您将结果放在更大的字符串中,请使用 格式化字符串文字 (3.6+) 或使用 str.format()
并将 format()
函数的第二个参数放在占位符的冒号之后 {:...}
:><预><代码>>>>值 = 14>>>f'生成的二进制输出为:{value:#010b}''产生的输出,以二进制表示:0b00001110'>>>'产生的输出,以二进制表示:{:#010b}'.format(value)'产生的输出,以二进制表示:0b00001110'
碰巧的是,即使只是格式化单个值(因此无需将结果放入更大的字符串中),使用格式化的字符串文字也比使用format()
更快:
但只有在紧密循环中的性能很重要时我才会使用它,因为 format(...)
可以更好地传达意图.
如果您不需要 0b
前缀,只需删除 #
并调整字段的长度:
I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:
Example:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
Is there a way of doing this?
Use the format()
function:
>>> format(14, '#010b')
'0b00001110'
The format()
function simply formats the input following the Format Specification mini language. The #
makes the format include the 0b
prefix, and the 010
size formats the output to fit in 10 characters width, with 0
padding; 2 characters for the 0b
prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format()
and put the second argument for the format()
function after the colon of the placeholder {:..}
:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format()
:
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...)
communicates the intent better.
If you did not want the 0b
prefix, simply drop the #
and adjust the length of the field:
>>> format(14, '08b')
'00001110'
这篇关于转换为二进制并保留前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!