Python各進位間的轉換

來源:互聯網
上載者:User

標籤: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各進位間的轉換

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.