The Python function bin() returns the binary representation of a given integer.
In case a non-integer class is given, the __index__() method is used.
bin() on integer
int1 = 5
print(bin(int1))
In this example, the binary representation of the integer is returned. The prefix 0b is included to indicate a binary representation.
0b101
remove prefix
To remove the prefix, we slice off the prefix:
int1 = 5
print(bin(int1)[2:])
to receive just the binary code:
101
reverse bin() function
To reverse the bin() function we simply use the int() function:
int1 = 5
bin1 = bin(int1)
print(int(bin1, 2))
to receive the original integer again:
5
bin() on non-integer
class Calc:
a=2.5
b=2.5
def __index__(self):
return int(self.a + self.b);
calc1 = Calc()
print(bin(calc1))
The binary representation of the sum 5 is returned:
0b101
bin() syntax
The syntax of the bin() function is:
bin(integer)
bin() arguments
The bin() function takes exactly one argument of type integer.
If more or less than one argument is given, a TypeError exception is raised.
If a non-integer type is given, a TypeError exception is raised as well.
bin() return values
The bin() function returns the binary representation of a given integer. The return value is prefixed with 0b, and the type of the return value is str.