python里的进制转换并不复杂,大家只需要记住,目标进制为2进制时,就用bin(),目标进制是8进制的时候用oct(),目标进制是10进制的时候用int(),目标进制是16进制的时候用hex()
#coding=utf-8
'''
Created on 2016-3-28
@author: Administrator
'''
class NumberType():
Binary = 1
Eigth = 2
Decimal = 3
Hex = 4
def transfer_number(str_number,oldtype,newtype):
number = ''
if oldtype == NumberType.Binary:
if newtype == NumberType.Eigth:
number = oct(int(str_number, 2))
if newtype == NumberType.Decimal:
number = int(str_number,2)
if newtype == NumberType.Hex:
number = hex(int(str_number,2))
if oldtype == NumberType.Decimal:
if newtype == NumberType.Binary:
number = bin(int(str_number))
if newtype == NumberType.Eigth:
number = oct(int(str_number))
if newtype == NumberType.Hex:
number = hex(int(str_number))
if oldtype == NumberType.Eigth:
if newtype == NumberType.Binary:
number = bin(int(str_number, 8))
if newtype == NumberType.Decimal:
number = int(str_number, 8)
if newtype == NumberType.Hex:
number = hex(int(str_number, 8))
if oldtype == NumberType.Hex:
if newtype == NumberType.Binary:
number = bin(int(str_number, 16))
if newtype == NumberType.Eigth:
number = oct(int(str_number, 16))
if newtype == NumberType.Decimal:
number = int(str_number, 16)
return str(number)
if __name__ =='__main__':
print transfer_number('2054', NumberType.Decimal, NumberType.Hex)