在python中将十进制转换为二进制

Pau*_*aul 127 python binary decimal

我可以使用python中的任何模块或函数将十进制数转换为二进制数吗?我能够使用int('[binary_value]',2)将二进制转换为十进制,所以任何方法都可以在不编写代码的情况下自行完成

aar*_*ing 205

所有数字都以二进制形式存储.如果您想要二进制给定数字的文本表示,请使用bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10
Run Code Online (Sandbox Code Playgroud)

  • 误导。bin() 返回二进制 *string*,而不是二进制 (4认同)

Mat*_*son 70

"{0:#b}".format(my_int)
Run Code Online (Sandbox Code Playgroud)

  • 这是使用前导零打印的格式:`"{0:08b}".format(my_int)` (35认同)

use*_*036 53

没有前面的0b:

"{0:b}".format(int)
Run Code Online (Sandbox Code Playgroud)

从Python 3.6开始,您还可以使用格式化的字符串文字f-string,--- PEP:

f"{int:b}"
Run Code Online (Sandbox Code Playgroud)

  • 您还可以确定以这种方式表示的位数:>>> `"{:0>15b}".format(3)` >>> '000000000000011' (2认同)

小智 35

def dec_to_bin(x):
    return int(bin(x)[2:])
Run Code Online (Sandbox Code Playgroud)

就这么简单.

  • ** - 1** - 不返回int.另外,`dec_to_bin(-1)`给出了'ValueError:int()的无效文字,基数为10:'b1' (13认同)
  • @Wallace:因为二进制和十进制是如何_显示_数字的选择,而不是数字本身的一部分。`dec_to_bin(0b101) == 101`,这是无意义的,因为您可以应用于 101 的任何操作都与原始 5 没有任何关系 - 例如,`dec_to_bin(0b101) + 1 == 102`。 (3认同)
  • 你能解释一下 [2:] 吗? (2认同)
  • 试试`bin(2)`.你不会得到'10'.你得到'0b10'.与`hex(2)`('0x2')相同的可能坑.所以你想要除了前两个字符之外的所有字符.所以你采取一个在前两个字符后面开始的切片. (2认同)

flo*_*onk 12

您还可以使用numpy模块中的函数

from numpy import binary_repr
Run Code Online (Sandbox Code Playgroud)

它也可以处理前导零:

Definition:     binary_repr(num, width=None)
Docstring:
    Return the binary representation of the input number as a string.

    This is equivalent to using base_repr with base 2, but about 25x
    faster.

    For negative numbers, if width is not given, a - sign is added to the
    front. If width is given, the two's complement of the number is
    returned, with respect to that width.
Run Code Online (Sandbox Code Playgroud)


ins*_*get 8

我同意@ aaronasterling的回答.但是,如果您想要一个可以转换为int的非二进制字符串,那么您可以使用规范算法:

def decToBin(n):
    if n==0: return ''
    else:
        return decToBin(n/2) + str(n%2)
Run Code Online (Sandbox Code Playgroud)

  • @aaron,后一点可以通过切换到`//`(截断分割)来解决; 前者,通过切换两个字符串的顺序在`return`中求和.不管怎么说递归都没有任何意义(`bin(n)[2:]` - 或者如果你被困在一些旧版本的Python上,那么`while`循环 - 将会更好!). (4认同)
  • @Timo 哈哈,显然你使用的是 Python3,只需将 `binary(n/2)` 更改为 `binary(n//2)` 那么你就不会得到总线负载:-) (2认同)

小智 6

n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))
Run Code Online (Sandbox Code Playgroud)