资源描述:
《python内置函数进制转换用法》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、使用Python内置函数:bin()、oct()、int()、hex()可实现进制转换。先看Python官方文档中对这几个内置函数的描述:bin(x)Convertanintegernumbertoabinarystring.TheresultisavalidPythonexpression.IfxisnotaPythonintobject,ithastodefinean__index__()methodthatreturnsaninteger.oct(x)Convertanintegernumbertoanoctal
2、string.TheresultisavalidPythonexpression.IfxisnotaPythonintobject,ithastodefinean__index__()methodthatreturnsaninteger.int([number
3、string[,base]])Convertanumberorstringtoaninteger.Ifnoargumentsaregiven,return0.Ifanumberisgiven,returnnumber.__int__().Conversionof
4、floatingpointnumberstointegerstruncatestowardszero.Astringmustbeabase-radixintegerliteraloptionallyprecededby‘+’or‘-‘(withnospaceinbetween)andoptionallysurroundedbywhitespace.Abase-nliteralconsistsofthedigits0ton-1,with‘a’to‘z’(or‘A’to‘Z’)havingvalues10to35.Thed
5、efaultbaseis10.Theallowedvaluesare0and2-36.Base-2,-8,and-16literalscanbeoptionallyprefixedwith0b/0B,0o/0O,or0x/0X,aswithintegerliteralsincode.Base0meanstointerpretexactlyasacodeliteral,sothattheactualbaseis2,8,10,or16,andsothatint('010',0)isnotlegal,whileint('01
6、0')is,aswellasint('010',8).hex(x)Convertanintegernumbertoahexadecimalstring.TheresultisavalidPythonexpression.IfxisnotaPythonintobject,ithastodefinean__index__()methodthatreturnsaninteger.↓2进制8进制10进制16进制2进制-bin(int(x,8))bin(int(x,10))bin(int(x,16))8进制oct(int(x,2
7、))-oct(int(x,10))oct(int(x,16))10进制int(x,2)int(x,8)-int(x,16)16进制hex(int(x,2))hex(int(x,8))hex(int(x,10))-bin()、oct()、hex()的返回值均为字符串,且分别带有0b、0o、0x前缀。Python进制转换(二进制、十进制和十六进制)实例#!/usr/bin/envpython#-*-coding:utf-8-*-#2/10/16basetrans.wrotebysrcdogon20th,April,2009
8、#ldelementsinbase2,10,16.importos,sys#globaldefinition#base=[0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F]base=[str(x)forxinrange(10)]+[chr(x)forxinrange(ord('A'),ord('A')+6)]#bin2dec#二进制to十进制:int(str,n=10)defbin2dec(string_num):returnstr(int(string_num,2))#hex2dec#十六进制to十进制
9、defhex2dec(string_num):returnstr(int(string_num.upper(),16))#dec2bin#十进制to二进制:bin()defdec2bin(string_num):num=int(string_num)mid=[]whileTrue:ifnum==0:breaknum,rem=div