Python achieve conversion between decimal and binary

Binary Decimal turn

  • Principle: The addition modulo 2, the output in reverse order.
  • Implementation: decimal integer divisible by 2, can get a quotient and a remainder; then removing provider 2, will get a quotient and a remainder, so until the time until the supplier of less than 1, and then sorted to obtain sequentially inverted binary number, in Python we adopt "//" (except the floor) ways to achieve the conversion
# 十进制整数转二进制
def decToBin(num):
    arry = []   #定义一个空数组,用于存放2整除后的商
    while True:
        arry.append(str(num % 2))  #用列表的append方法追加
        num = num // 2   #用地板除求num的值
        if num == 0:     #若地板除后的值为0,那么退出循环
            break

    return "".join(arry[::-1]) #列表切片倒叙排列后再用join拼接

print(decToBin(10))

输出结果:1010

Binary Coded Decimal

  • Principle: To right to left with each binary number to a power of 2 multiplied by the corresponding cumulative demand.
# 二进制整数转十进制
def binToDec(binary):
    result = 0   #定义一个初始化变量,后续用于存储最终结果
    for i in range(len(binary)):
        #利用for循环及切片从右至左依次取出,然后再用内置方法求2的次方
        result += int(binary[-(i + 1)]) * pow(2, i)

    return result

print(binToDec("1010"))
结果:10

Guess you like

Origin www.cnblogs.com/ddpeng/p/11302368.html