English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Python flow control

Fonction en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python bin() usage and examples

Python built-in functions

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)

bin() parameter

The bin() method takes one parameter:

  • num-To calculate the integer that represents its binary equivalent.
    If it is not an integer, the __index__() method should be implemented to return an integer.

bin() return value

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.

Example1:Use bin() to convert an integer to binary

number = 5
print('equivalent to5The binary is:

When running the program, the output is:

equivalent to5The binary is: 0b101

prefix0bThe result is represented as a binary string.

Example2:Convert the object to a binary file that implements the __index__ () method

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 cause 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.

Python built-in functions