#coding = utf-8
'''
Created on 2015年5月28日
二进制、八进制、十进制、十六进制之间进行相互转换
'''
class nsc():
hex_num={0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'a',11:'b',12:'c',13:'d',14:'e',15:'f'}
num_hex={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'a':10,'b':11,'c':12,'d':13,'e':14,'f':15}
'''二进制转十进制'''
def bin2dec(self,num):
#根据二进制的位数来计算
result=0
for i in str(num):
result=result*2+int(i)
return result
'''二进制转八进制'''
def bin2oct(self,num):
result = ''
temp=list(str(num))
insert=3-len(temp)%3
while insert and insert !=3:
temp.insert(0, 0)
insert-=1
while temp:
result=str(int(temp.pop())*1+int(temp.pop())*2+int(temp.pop())*4)+result
return int(result)
'''二进制转十六进制'''
def bin2hex(self,num):
result = ''
temp=list(str(num))
insert=4-len(temp)%4
while insert and insert!=4:
insert-=1
temp.insert(0, 0)
while temp:
#TODO 格式化输出
x=int(temp.pop())*1+int(temp.pop())*2+int(temp.pop())*4+int(temp.pop())*8
result=self.hex_num[x]+result
return result
'''十进制转二进制'''
def dec2bin(self,num):
#除2取余,逆序排列
result=''
temp=[]
while num:
temp.append(num%2)
num=num//2
while temp:
result+=str(temp.pop())
return int(result)
'''十进制转八进制'''
def dec2oct(self,num):
return self.bin2oct(self.dec2bin(num))
'''十进制转十六进制'''
def dec2hex(self,num):
return self.bin2hex(self.dec2bin(num))
'''十六进制转二进制'''
def hex2bin(self,num):
hex_n=list(str(num))
result=''
for i in hex_n:
result+=str(self.dec2bin(self.num_hex[i]))
return result
'''十六进制转八进制'''
def hex2oct(self,num):
return self.bin2oct(self.hex2bin(num))
'''十六进制转十进制'''
def hex2dec(self,num):
return self.bin2dec(self.hex2bin(num))
if __name__=='__main__':
nc=nsc()
print(nc.hex2dec('fffee'))
转载于:https://www.cnblogs.com/lkpp/p/7400058.html
相关资源:Python中不同进制互相转换(二进制、八进制、十进制和十六进制)