English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The bin() method converts and returns the binary equivalent string of the given integer. If the parameter is not an integer, the __index__() method must be implemented to return an integer.
The syntax of the bin() method is:
bin(num)
The bin() method takes one parameter:
num-To calculate the integer whose binary equivalent you want to find.
If it is not an integer, the __index__() method should be implemented to return an integer.
The bin() method returns a binary string equivalent to the given integer.
If an integer is not specified, a TypeError exception will be raised, highlighting that the type cannot be interpreted as an integer.
number = 5 print('Is equivalent to5The binary is: ', bin(number))
When running the program, the output is:
Is equivalent to5The binary is: 0b101
Prefix0bThe result is represented as a binary string.
class Quantity: apple = 1 orange = 2 grapes = 2 def __index__(self): return self.apple + self.orange + self.grapes print('The binary equivalent of quantity:', bin(Quantity()))
When running the program, the output is:
The binary equivalent of quantity is: 0b101
Here, we have sent an object of the class Quantity to the bin() method.
Even if the object 'quantity' is not an integer, the bin() method will not raise an error.
This is because we have implemented a method that returns an integer (the sum of the number of fruits) with __index__(). Then this integer is provided to the bin() method.