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)
Mat*_*son 70
"{0:#b}".format(my_int)
Run Code Online (Sandbox Code Playgroud)
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)
小智 35
def dec_to_bin(x):
return int(bin(x)[2:])
Run Code Online (Sandbox Code Playgroud)
就这么简单.
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)
我同意@ aaronasterling的回答.但是,如果您想要一个可以转换为int的非二进制字符串,那么您可以使用规范算法:
def decToBin(n):
if n==0: return ''
else:
return decToBin(n/2) + str(n%2)
Run Code Online (Sandbox Code Playgroud)
小智 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)
归档时间: |
|
查看次数: |
403236 次 |
最近记录: |