Python進位轉換

來源:互聯網
上載者:User

標籤:精度   技術分享   format   rate   targe   技術   oct   enumerate   image   

一 內建函數

  bin()、oct()、hex()的傳回值均為字串,且分別帶有0b、0o、0x首碼。

執行個體 統計位元裡1的個數

def countBits(n):    return bin(n).count("1")countBits(4)
二 format
In [54]: ‘{:b}‘.format(17)Out[54]: ‘10001‘In [55]: ‘{:d}‘.format(17)Out[55]: ‘17‘In [56]: ‘{:o}‘.format(17)Out[56]: ‘21‘In [57]: ‘{:x}‘.format(17)Out[57]: ‘11‘

  執行個體 求兩個二進位字串的和 不能用內建函數

def toDecimal(num):    return  sum( (b == ‘1‘)*2**i  for i,b in enumerate(num[::-1]))  def add(a,b):    return ‘{:b}‘.format(toDecimal(a) + toDecimal(b))add(‘111‘,‘10‘)‘1001‘ #這裡沒有首碼

此外format還有很多其他功能,控制精度,對齊等格式化輸出。

上面統計1的個數也可以寫成

def countBits(n):    return ‘{:b}‘.format(n).count(‘1‘)

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.