標籤:python 進位轉換 二進位 八進位
表示各進位的符號:
b:二進位,o:八進位,d:十進位,x:十六進位
bin()、oct()、hex()傳回值均為字串,且分別帶有0b、0o、0x首碼。
1、十進位轉二進位
>>> bin(10)‘0b1010‘>>> ‘{0:b}‘.format(10)‘1010‘
這兩種方法返回的都是二進位的字串表示。
對十進位數直接轉二進位
list1 = []if num <= 1 and num >= 0: print "二進位:%d" %(num)else : while num > 1 : list1.append(str(num % 2)) num /= 2 list1.append(str(num)) list1.reverse()
2、十進位轉八進位
>>> oct(12)‘014‘>>> ‘{0:o}‘.format(12)‘14‘
3、十進位轉十六進位
>>> hex(12)‘0xc‘>>> ‘{0:x}‘.format(12)‘c‘
4、二進位轉十進位
>>> int(‘1010‘,2)10>>> eval(‘0b10‘)2
int(string_num, n):
string_num:進位的字串表示
n:表示string_num是多少進位的數
5、八進位轉十進位
>>> int(‘014‘,8)12>>> ‘{0:d}‘.format(014)‘12‘>>> eval(‘0o10‘)8
6、十六進位轉十進位
>>> ‘{0:d}‘.format(0xc)‘12‘>>> int(‘0xc‘,16)12>>> eval(‘0x10‘)16
注意:
hex函數比格式化字串函數format慢,不推薦使用。
eval函數比int函數慢,不推薦使用。
二進位、十六進位、八進位之間的轉換,可以藉助十進位這個中間值,即先轉十進位再轉其他進位,也可以直接使用函數進行轉換。如:
十六進位轉二進位:
#藉助十進位>>> bin(int(‘fc‘,16))‘0b11111100‘#利用函數直接轉>>> bin(0xa)‘0b1010‘>>> oct(0xa)‘012‘>>> hex(10)‘0xa‘
著作權聲明:本文為博主原創文章,可以轉載,但得註明出處。更多精彩文章請關注公眾號:gloryroadtrain
Python各進位間的轉換