转换为二进制并在 Python 中保留前导零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16926130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:01:28  来源:igfitidea点击:

Convert to binary and keep leading zeros in Python

pythonbinaryformattingbitwise-operators

提问by Niels S?nderb?k

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:

我正在尝试使用 Python 中的 bin() 函数将整数转换为二进制。但是,它始终删除我实际需要的前导零,因此结果始终为 8 位:

Example:

例子:

bin(1) -> 0b1

# What I would like:
bin(1) -> 0b00000001

Is there a way of doing this?

有没有办法做到这一点?

采纳答案by Martijn Pieters

Use the format()function:

使用format()功能

>>> format(14, '#010b')
'0b00001110'

The format()function simply formats the input following the Format Specification mini language. The #makes the format include the 0bprefix, and the 010size formats the output to fit in 10 characters width, with 0padding; 2 characters for the 0bprefix, the other 8 for the binary digits.

format()函数只是按照格式规范迷你语言格式化输入。在#使格式包括0b前缀,而010大小格式的输出,以适应在10个字符宽,与0填充; 2 个字符为0b前缀,另外 8个字符为二进制数字。

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 {:..}:

如果要将结果放入更大的字符串,请使用格式化的字符串文字(3.6+) 或使用str.format()并将format()函数的第二个参数放在占位符的冒号之后{:..}

>>> 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():

碰巧的是,即使只是格式化单个值(因此不将结果放入更大的字符串中),使用格式化的字符串文字比使用更快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.

但只有在紧密循环中的性能很重要时,我才会使用它,因为format(...)可以更好地传达意图。

If you did not want the 0bprefix, simply drop the #and adjust the length of the field:

如果您不想要0b前缀,只需删除#并调整字段的长度:

>>> format(14, '08b')
'00001110'

回答by Peter Varo

You can use the string formatting mini language:

您可以使用字符串格式化迷你语言:

def binary(num, pre='0b', length=8, spacer=0):
    return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])

Demo:

演示:

print binary(1)

Output:

输出:

'0b00000001'

EDIT:based on @Martijn Pieters idea

编辑:基于@Martijn Pieters 的想法

def binary(num, length=8):
    return format(num, '#0{}b'.format(length + 2))

回答by bwbrowning

>>> '{:08b}'.format(1)
'00000001'

See: Format Specification Mini-Language

请参阅:格式规范迷你语言



Note for Python 2.6 or older, you cannot omit the positional argument identifier before :, so use

注意对于 Python 2.6 或更早版本,您不能省略 之前的位置参数标识符:,因此请使用

>>> '{0:08b}'.format(1)
'00000001'      

回答by Adam

You can use something like this

你可以使用这样的东西

("{:0%db}"%length).format(num)

回答by rekinyz

I am using

我在用

bin(1)[2:].zfill(8)

will print

将打印

'00000001'

回答by Anshul Garg

You can use zfill:

您可以使用 zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2)

prints:

印刷:

01
10
100

I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable... e.g. - x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.

我喜欢这个解决方案,因为它不仅在输出数字时有用,而且在您需要将其分配给变量时也有帮助......例如 - x = str(datetime.date.today().month).zfill(2) 将将 2 月份的 x 返回为“02”。

回答by Mark

Sometimes you just want a simple one liner:

有时您只想要一个简单的衬里:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3

蟒蛇 3

回答by ruohola

When using Python >= 3.6, the cleanest way is to use f-stringswith string formatting:

使用 Python 时>= 3.6,最简洁的方法是使用带有字符串格式的f字符串

>>> var = 23
>>> f"{var:#010b}"
'0b00010111'

Explanation:

解释:

  • varthe variable to format
  • :everything after this is the format specifier
  • #use the alternative form (adds the 0bprefix)
  • 0pad with zeros
  • 10pad to a total length off 10 (this includes the 2 chars for 0b)
  • buse binary representation for the number
  • var要格式化的变量
  • :此后的所有内容都是格式说明符
  • #使用替代形式(添加0b前缀)
  • 0用零填充
  • 10填充到 10 的总长度(这包括 2 个字符0b
  • b使用二进制表示数字

回答by Jaydeep Mahajan

you can use rjust string method of python syntax: string.rjust(length, fillchar) fillchar is optional

你可以使用 python 语法的 rjust 字符串方法: string.rjust(length, fillchar) fillchar 是可选的

and for your Question you acn write like this

对于您的问题,您可以这样写

'0b'+ '1'.rjust(8,'0)

so it wil be '0b00000001'

所以它将是'0b00000001'