The bin()
function is one of Python's built-in functions that converts an integer to its binary string representation.
Specifically, the bin()
function returns a string containing the binary representation of the integer argument, prefixed with 0b
.
For example:
print(bin(42)) # Output: '0b101010'
In this example, the integer 42
is converted to the binary string 101010
with the 0b
prefix, resulting in the final output string 0b101010
.
You can remove the 0b
prefix using string slicing:
print(bin(42)[2:]) # Output: '101010'
If the argument is not an int
object, it must define an __index__()
method that returns an integer:
class mytype:
def __index__(self):
return 0
a = mytype()
print(bin(a))