在Python中,有没有可以将十进制数转换为二进制的模块或函数呢?我知道可以使用int('[binary_value]',2)将二进制转换为十进制,但是否有任何方法可以避免自己编写代码进行反向转换呢?
在Python中,有没有可以将十进制数转换为二进制的模块或函数呢?我知道可以使用int('[binary_value]',2)将二进制转换为十进制,但是否有任何方法可以避免自己编写代码进行反向转换呢?
所有数字都是以二进制形式存储。如果您想要一个给定数字的文本表示形式,请使用bin(i)
>>> bin(10)
'0b1010'
>>> 0b1010
10
TypeError: 非空格式字符串传递给object.__format__
。 - Right leg---> '101111'
- Josef Klotzner"{:0>15b}".format(3)
>>> '000000000000011' - MissSergeivnaformat(int_value, 'b')
。 - Arye P."{0:#b}".format(my_int)
"{0:08b}".format(my_int)
,其中my_int
是要打印的整数。 - Waldo Bronchartdef dec_to_bin(x):
return int(bin(x)[2:])
如此简单。
dec_to_bin(-1)
会出现ValueError: invalid literal for int() with base 10: 'b1'
的错误提示。 - Ericbin(2)
。你不会得到'10',而是得到'0b10'。同样的问题也可能出现在hex(2)
中('0x2')。因此,你需要去掉前两个字符。你可以使用切片来从第三个字符开始截取。 - leewzdec_to_bin(0b101) == 101
这个说法是无意义的,因为你可以对101进行的任何操作都与原始的5没有任何关系,例如,dec_to_bin(0b101) + 1 == 102
。 - Ericfrom numpy import binary_repr
它还可以处理前导零:
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.
我同意@aaronasterling的答案。然而,如果你想要一个非二进制字符串,可以将其转换为int类型,那么你可以使用规范算法:
def decToBin(n):
if n==0: return ''
else:
return decToBin(n/2) + str(n%2)
int(bin(10), 2)
的结果是 10
。int(decToBin(10))
的结果是 101
,而 int(decToBin(10), 2)
的结果是 5
。此外,如果使用 from __future__ import division
或者 Python 3,你的函数会达到递归限制。 - aaronasterlingbin(n)[2:]
——或者如果您卡在某个旧版本的Python上,则使用while
循环会更好!)。 - Alex Martellibinary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
- Aziz Altoe-
的数字,还有在递归调用dectobin中。 - Timobinary(n/2)
更改为binary(n//2)
,那么你就不会遇到这个问题了 :-) - Aziz Altoif n==0: return '0'
而不是if n==0: return ''
,因为对于n=0,你的代码返回空字符串,这是错误的答案。虽然这种方法会在非零输入的左侧给你一个额外的0。 - user3342981n=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))
Get the integer and fractional part.
from decimal import *
a = Decimal(3.625)
a_split = (int(a//1),a%1)
Convert the fractional part in its binary representation. To achieve this multiply successively by 2.
fr = a_split[1]
str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...