Python binary conversion

Source: Internet
Author: User

A built-in function

The return values for Bin (), Oct (), and Hex () are all strings, with 0b, 0o, and 0x prefixes respectively.

Instance statistics number of 1 in binary number

def countbits (n):    return Bin (n). Count ("1") countbits (4)
Two format
In [si]: ' {: b} '. Format (out[54]: ' 10001 ' in []: ' {:d} '. Format (+) out[55]: ' + ' in [+]: ' {: o} '. Format (+) out[56]: ' 21 ' In []: ' {: x} '. Format (out[57]: ' 11 '

Instance to find two binary strings and cannot use built-in functions

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 ', ' ten ') ' 1001 ' #这里没有前缀

In addition format has many other functions, such as control accuracy, alignment, etc. formatted output.

The number of the above statistics 1 can also be written

def countbits (n):    return ' {: b} '. Format (n). Count (' 1 ')

Python binary conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.