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