Preface
Today I swiped LeetCode and saw a question that needs to be converted from decimal to binary. I found python on the Internet but built-in related functions. Record and learn!
bin function
bin(): Returns the binary string representation of an integer int or long int, 0b
starting with a prefix .
a = 4
print(bin(a)) # 0b100
print(type(bin(a))) # <class 'str'>
oct function
oct(): Convert an integer to an octal string, and the octal is represented 0o
as a prefix.
a = 9
print(oct(a)) # 0o11
print(type(oct(a))) # <class 'str'>
int function
int(): Used to convert a string or number to an integer, and the default is converted to decimal.
a = 0xA
print(int(a)) # 10
print(type(int(a))) # <class 'int'>
Convert a binary string to decimal:
a = '011'
print(int(a,2)) # 3
print(type(int(a))) # <class 'int'>
hex function
hex(): Used to convert a specified number into hexadecimal number.
a = 15
print(hex(a)) # 0xf
print(type(hex(a))) # <class 'str'>