VOOZH about

URL: https://www.geeksforgeeks.org/python/bin-in-python/

⇱ bin() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

bin() in Python

Last Updated : 15 Nov, 2023

Python bin() function returns the binary string of a given integer. bin() function is used to convert integer to binary string. In this article, we will learn more about Python bin() function.

Example

In this example, we are using the bin() function to convert integer to binary string.

Output

0b101010

Python bin() function Syntax

The bin() function in Python has the following syntax:

Syntax:  bin(a)

Parameters : a : an integer to convert

Return Value : A binary string of an integer or int object.

Exceptions : Raises TypeError when a float value is sent in arguments.

bin() in Python Examples

Let us see a few examples of the bin() function in Python for a better understanding.

Convert Integer to Binary String

In this example, we simply passed an integer to the bin() function, which allows you to convert integer to a binary string, returning the binary representation of that number.

Output

0b1100100

Convert integer to binary with a user-defined function

In this example, we created a user-defined function that takes an integer as the parameter and returns the binary representation of the number as a binary string, effectively convert the integer to a binary string after removing the '0b' characters that indicate that a number is in binary format.

Output

The binary representation of 100 (using bin()) is : 1100100

User-defined object to binary using bin() and __index()__

Here we send the object of the class to the bin methods, and we are using Python special methods __index()__ method which always returns a positive integer, and it can not be a rising error if the value is not an integer. 

Output

0b1100100
Comment