Python实现各种进制转换问题,so easy

Python实现进制转换问题,so easy
********************十进制转其他进制*************************************
#系统默认a,b值都是十进制
a = 6
b = 10
print('decimal of a and b are:',a, b)
print('binary of a and b are:',bin(a), bin(b))  #10进制到2进制
print('octonary of a and b are:', oct(a), oct(b)) #十进制转八进制
print('hexadecimal of a and b are:', hex(a),hex(b)) #十进制转16进制


decimal of a and b are: 6 10
binary of a and b are: 0b110 0b1010
octonary of a and b are: 0o6 0o12
hexadecimal of a and b are: 0x6 0xa
[Finished in 0.5s]
***************************base进制转10进制*******************************




print(int('1010', 2))# 二进制转10进制
print(int('f', 16)) #16进制转10进制
print(int('10',8))   #8进制转10进制
print(int('10',6))   #6进制转10进制


10
15
8
6

[Finished in 0.7s]
********************************int()函数官方解释*******************************

help(int)
函数得到如下关于int()函数的解释

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer  (base这里理解为进制的意思),意味着把字符串x(base进制)转化为对应的十进制
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.


int(x=0) -> integer int()函数把数字或者字符串转化为十进制的数字
int(x, base=10) -> integer  int()函数把字符串x(x是base进制格式)转化为10进制数字

说明base可以放2-36的数字,还有0。  base是几就把几进制转为10进制,也就是把base进制转为10进制


****************************十进制转其他进制******************************

def dec2base(num,base):#base就是其他进制
    l = []
    if num < 0:
        return '-' + dec2base(-num,base)
    while True:

        num, remainder = divmod(num, base)#divmod返回除数和余数
        #print(num,remainder)
        l.append(str(remainder)) #把余数添加到列表里面
        if num == 0:
            return ''.join(l[::-1])

print(dec2base(9,2))

****************其他进制转为10进制**********************

#16进制无法利用此函数
def base2dec(num,base):
    if num < 0:
        return '-' + str(base2dec(-num,base))
    sum = 0
    len_bin = len(str(num))
    for i in range(len_bin):
        
        sum = sum + int(str(num)[i])* (base**(len_bin -i-1))
        #print(i,int(str(num)[i]),len_bin -i-1,2**(len_bin -i-1))
    return sum
print(base2dec(-101,2))

猜你喜欢

转载自blog.csdn.net/btujack/article/details/80593731