python中bin(20)_Python bin()用法及代码示例

将小数转换为二进制始终是python dev项目和竞争性编程中所必需的重要实用程序。具有速记功能来实现此目的在需要快速转换而无需编写长代码的情况下总是很方便的,这由“ bin()”提供。本文对此进行了讨论。

将十进制转换为二进制的自编程方法

1.使用递归

# Function to print binary number for the

# input decimal using recursion

def decimalToBinary(n):

if n > 1:

# divide with integral result

# (discard remainder)

decimalToBinary(n//2)

print (n%2,end="")

# Driver code

if __name__ == '__main__':

decimalToBinary(8)

print("\r")

decimalToBinary(18)

print("\r")

decimalToBinary(7)

print

输出:

1000

10010

111

2.使用循环

# Python code to demonstrate naive method

# using loop

# function returning binary string

def Binary(n):

binary = ""

i = 0

while n > 0 and i<=8:

s1 = str(int(n%2))

binary = binary + s1

n /= 2

i = i+1

d = binary[::-1]

return d

print("The binary representation of 100 (using loops) is:",end="")

print(Binary(100))

输出:

The binary representation of 100 (using loops) is:001100100

使用bin()

使用bin()可以减少编码所需的时间,并且还可以消除上述两种方法中可能遇到的麻烦。

用法:

bin(a)

参数:

a: an integer to convert

返回值:

A binary string of an integer or int object.

Exceptions:

Raises TypeError when a float value is sent in arguments.

# Python code to demonstrate working of

# bin()

# function returning binary string

def Binary(n):

s = bin(n)

# removing "0b" prefix

s1 = s[2:]

return s1

print("The binary representation of 100 (using bin()) is:",end="")

print(Binary(100))

输出:

The binary representation of 100 (using bin()) is:1100100

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值