在Python中将int转换为二进制字符串
如何在 Python 中将整数转换为二进制字符串?
37 → '100101'
How do I convert an integer into a binary string in Python?
37 → '100101'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
Python 的字符串格式方法可以采用格式规范。
Python 2 的格式规范文档
Python 3 的格式规范文档
Python's string format method can take a format spec.
Format spec docs for Python 2
Format spec docs for Python 3
如果您正在寻找
bin()
作为相当于hex()
,它是在 python 2.6 中添加的。例子:
If you're looking for
bin()
as an equivalent tohex()
, it was added in python 2.6.Example:
实际上,Python确实为此内置了一些功能,能够执行
'{0:b}'.format(42)
等操作,这将为您提供42
或101010
的位模式(字符串)。对于更普遍的哲学来说,没有一种语言或库能够为其用户群提供他们想要的一切。 如果您工作的环境不能完全提供您所需要的内容,那么您应该在开发时收集代码片段,以确保您永远不必编写相同的内容两次。 例如,伪代码:
它将根据十进制值构造二进制字符串。 请记住,这是一段通用的伪代码,它可能不是最有效的方法,但对于您似乎建议的迭代,它不会产生太大的影响。 它实际上只是作为如何完成的指南。
总体思路是使用以下代码(按优先顺序):
Python actually does have something already built in for this, the ability to do operations such as
'{0:b}'.format(42)
, which will give you the bit pattern (in a string) for42
, or101010
.For a more general philosophy, no language or library will give its user base everything that they desire. If you're working in an environment that doesn't provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example, the pseudo-code:
which will construct your binary string based on the decimal value. Just keep in mind that's a generic bit of pseudo-code which may not be the most efficient way of doing it though, with the iterations you seem to be proposing, it won't make much difference. It's really just meant as a guideline on how it could be done.
The general idea is to use code from (in order of preference):
我很惊讶没有提到使用 Python 3.6 及更高版本支持的格式化字符串来完成此操作的好方法。 TLDR:
更长的故事
这是 Python 3.6 中提供的格式化字符串的功能:
您也可以请求二进制:
指定宽度:
请求零填充:
并添加公共前缀来表示二进制数:
您也可以让 Python 为您添加前缀,但是我不像上面的版本那么喜欢它,因为你必须考虑前缀的宽度:
更多信息可在 格式化字符串文字 和 格式规范迷你语言。
I am surprised there is no mention of a nice way to accomplish this using formatting strings that are supported in Python 3.6 and higher. TLDR:
Longer story
This is functionality of formatting strings available from Python 3.6:
You can request binary as well:
Specify the width:
Request zero padding:
And add common prefix to signify binary number:
You can also let Python add the prefix for you but I do not like it so much as the version above because you have to take the prefix into width consideration:
More info is available in official documentation on Formatted string literals and Format Specification Mini-Language.
如果你想要一个没有 0b 前缀的文本表示,你可以使用这个:
当你想要一个 n 位表示时:
或者,如果你更喜欢有一个函数:
If you want a textual representation without the 0b-prefix, you could use this:
When you want a n-bit representation:
Alternatively, if you prefer having a function:
作为参考:
此函数可以转换大到
18446744073709551615
的正整数,表示为字符串'1111111111111111111111111111111111111111111111111111111111111111'
。可以对其进行修改以提供更大的整数,尽管它可能不如
"{0:b}".format()
或bin()
那么方便。As a reference:
This function can convert a positive integer as large as
18446744073709551615
, represented as string'1111111111111111111111111111111111111111111111111111111111111111'
.It can be modified to serve a much larger integer, though it may not be as handy as
"{0:b}".format()
orbin()
.这是针对 python 3 的,它保留了前导零!
This is for python 3 and it keeps the leading zeros !
一种简单的方法是使用字符串格式,请参阅此页面 。
如果您想要固定长度的二进制字符串,您可以使用以下命令:
如果需要二进制补码,则可以使用以下行:
其中 n 是二进制字符串的宽度。
A simple way to do that is to use string format, see this page.
And if you want to have a fixed length of the binary string, you can use this:
If two's complement is required, then the following line can be used:
where n is the width of the binary string.
带有 lambda 的单行代码:
测试:
编辑:
但是然后:(
相比之下
one-liner with lambda:
test:
EDIT:
but then :(
in compare to
由于前面的答案大多使用format(),
这是一个 f 字符串实现。
输出:
为了方便起见,这里是格式化字符串文字的 python 文档链接: https:/ /docs.python.org/3/reference/lexical_analysis.html#f-strings。
As the preceding answers mostly used format(),
here is an f-string implementation.
Output:
For convenience here is the python docs link for formatted string literals: https://docs.python.org/3/reference/lexical_analysis.html#f-strings.
替代方案摘要:
贡献者包括 John Fouhy、Tung阮,mVChr,
Summary of alternatives:
Contributors include John Fouhy, Tung Nguyen, mVChr, Martin Thoma. and Martijn Pieters.
对于我们这些需要将有符号整数(范围 -2**(digits-1) 到 2**(digits-1)-1)转换为 2 的补码二进制字符串的人来说,这是可行的:
这会产生:
For those of us who need to convert signed integers (range -2**(digits-1) to 2**(digits-1)-1) to 2's complement binary strings, this works:
This produces:
你可以这样做:
或:
you can do like that :
or :
使用 numpy pack/unpackbits,它们是你最好的朋友。
Using numpy pack/unpackbits, they are your best friends.
接受的答案没有解决负数,我将对此进行介绍。
除了上面的答案之外,您还可以使用 bin 和十六进制函数。 相反,使用二进制表示法:
但对于负数,事情会变得更复杂一些。 该问题没有指定您希望如何处理负数。
Python 只是添加一个负号,因此 -37 的结果将是这样的:
在计算机/硬件二进制数据中,负号不存在。 我们只有 1 和 0。 因此,如果您正在读取或生成要由其他软件/硬件处理的二进制数据流,您需要首先了解所使用的符号。
一种表示法是符号幅度表示法,其中第一位表示负号,而其余的是实际值。 在这种情况下,-37 将是
0b1100101
,37 将是0b0100101
。 这看起来像 python 生成的结果,但只需在前面添加 0 或 1 表示正/负数。更常见的是 二进制补码表示法,看起来更复杂,结果也大不相同来自 python 的字符串格式。 您可以阅读链接中的详细信息,但对于 8 位有符号整数,-37 将是
0b11011011
,37 将是0b00100101
。Python 没有简单的方法来生成这些二进制表示。 您可以使用 numpy 将二进制补码值转换为 python 整数:
但是我不知道用内置函数做相反的事情的简单方法。 bitstring 包 可以提供帮助。
The accepted answer didn't address negative numbers, which I'll cover.
In addition to the answers above, you can also just use the bin and hex functions. And in the opposite direction, use binary notation:
But with negative numbers, things get a bit more complicated. The question doesn't specify how you want to handle negative numbers.
Python just adds a negative sign so the result for -37 would be this:
In computer/hardware binary data, negative signs don't exist. All we have is 1's and 0's. So if you're reading or producing binary streams of data to be processed by other software/hardware, you need to first know the notation being used.
One notation is sign-magnitude notation, where the first bit represents the negative sign, and the rest is the actual value. In that case, -37 would be
0b1100101
and 37 would be0b0100101
. This looks like what python produces, but just add a 0 or 1 in front for positive / negative numbers.More common is Two's complement notation, which seems more complicated and the result is very different from python's string formatting. You can read the details in the link, but with an 8bit signed integer -37 would be
0b11011011
and 37 would be0b00100101
.Python has no easy way to produce these binary representations. You can use numpy to turn Two's complement binary values into python integers:
But I don't know an easy way to do the opposite with builtin functions. The bitstring package can help though.
Python 3.6 添加了一种新的字符串格式化方法,称为格式化字符串文字或“f-string”。
示例:
输出将为“Hello, Bob, your number is 00001010!”
关于这个问题的讨论可以在这里找到 - 这里
Python 3.6 added a new string formatting approach called formatted string literals or “f-strings”.
Example:
Output will be 'Hello, Bob, your number is 00001010!'
A discussion of this question can be found here - Here
另一种解决方案是使用另一种算法,即使用按位运算符。
无需反转字符串的更快版本。
Yet another solution with another algorithm, by using bitwise operators.
A faster version without reversing the string.
numpy。 binary_repr(num, width=None)
上面文档链接中的示例:
numpy.binary_repr(num, width=None)
Examples from the documentation link above:
输出:
output:
这是我刚刚实现的代码。 这不是一个方法,但您可以将其用作即用型函数!
Here is the code I've just implemented. This is not a method but you can use it as a ready-to-use function!
具有 DEC、BIN、HEX 所有必要功能的计算器:
(使用Python 3.5制作并测试)
您可以更改输入的测试数字并获取转换后的测试数字。
Calculator with all neccessary functions for DEC,BIN,HEX:
(made and tested with Python 3.5)
You can change the input test numbers and get the converted ones.
除非我误解了二进制字符串的含义,否则我认为您正在寻找的模块是 结构
Unless I'm misunderstanding what you mean by binary string I think the module you are looking for is struct
有点类似的解决方案
Somewhat similar solution
这是使用 divmod() 函数的简单解决方案,它返回提醒和不带分数的除法结果。
here is simple solution using the divmod() fucntion which returns the reminder and the result of a division without the fraction.
这是使用常规数学的另一种方法,没有循环,只有递归。 (简单情况 0 不返回任何内容)。
Here's yet another way using regular math, no loops, only recursion. (Trivial case 0 returns nothing).
我找到了一种使用矩阵运算将十进制转换为二进制的方法。
E
为输入的十进制数据,M
为二进制指令。bindata
为输出二进制数据,格式为1×M二进制矩阵。I found a method using matrix operation to convert decimal to binary.
E
is input decimal data,M
is the binary orders.bindata
is output binary data, which is in a format of 1 by M binary matrix.