Full text at a glance
Programming questions often involve converting the int type into binary and then performing operations. In addition to inventing the while loop on site, is there an easier way to implement it?
1. Convert to binary
1.1 bin function
bin is python's built-in function that converts int type into binary:
we only need to intercept based on the return value of the bin function to receive:
>>> a = 7
>>> b = bin(a)[2:]
>>> b
'111'
1.2 format function
The format function can control the output form of the numbers to be printed, and can be converted to binary through the ":b" method:
>>> a = 7
>>> b = '{0:b}'.format(a)
>>> b
'111'
>>> c = '{:b}'.format(a)
>>> c
'111'
When converting only a number, the placeholder "0" can be omitted.
1.3 f-string format
The f-string format is actually a simplified way of writing the format function:
>>> a = 7
>>> b = f'{
a:b}'
>>> b
'111'
2. Convert to octal and hexadecimal
2.1 Octal system
Octal conversion requires the use of the oct function and the ":o" format:
>>> a = 17
>>> o1 = oct(a)[2:]
>>> o2 = '{0:o}'.format(a)
>>> o3 = f'{
a:o}'
>>> o1 == o2 == o3 == '21'
True
2.2 Hexadecimal
Hexadecimal conversion requires the hex function and ":x" format:
>>> a = 37
>>> h1 = hex(a)[2:]
>>> h2 = '{0:x}'.format(a)
>>> h3 = f'{
a:x}'
>>> h1 == h2 == h3 == '25'
True
3. Convert back to decimal
The int function returns decimal by default, and the base parameter needs to be determined based on the number being converted. For example: when converting binary numbers, you need to set base to 2, when converting octal numbers, you need to set base to 8... Among them, "base=" can be omitted.
Whether to add "0b", "0o" and other prefixes does not affect the result:
>>> int('0b111', base=2)
7
>>> int('0b111', 2)
7
>>> int('111', 2)
7
>>> int('111', 2) == int('0b111', base=2) == 7
True
>>> int('21', 8) == int('0o21', base=8) == 17
True
>>> int('25', 16) == int('0x25', base=16) == 37
True
For more usage methods and applications of python, please pay attention to subsequent updates~