从十进制转其他进制是非常简单的,无非是分为两步:
- 将这个数对要转换的进制数相除,取余数,如
num%8
,继续拿着除之后的整数部分对进制数取余数,直到整数部分为0为止 - 将余数倒序输出,即可得到结果
num = input('input an int number: ')
t = input('input type(2,8,16): ')
def trans(num):
m = 0
lst = []
if t==16:
standar_result = hex(num)
result = '(16)'
elif t==8:
standar_result = oct(num)
result = '(8)'
elif t==2:
standar_result = bin(num)
result = '(2)'
while(num!=0):
q = num%t
num = num/t
lst.append(q)
m+=1
lst = lst[::-1]#倒序
for item in lst:#十六进制10以上的数要转为字母
if item ==10:
item = 'a'
elif item ==11:
item = 'b'
elif item ==12:
item = 'c'
elif item ==13:
item = 'd'
elif item ==14:
item = 'e'
elif item ==15:
item = 'f'
s = str(item)
result+=s
return result,standar_result
print 'result=%s\nstandar_result=%s'%(trans(num))
运行:
例1.
input an int number: 543
input type(2,8,16): 8
result=(8)1037
standar_result=01037
例2.
input an int number: 543
input type(2,8,16): 16
result=(16)21f
standar_result=0x21f
例3.
input an int number: 431
input type(2,8,16): 2
result=(2)110101111
standar_result=0b110101111