bin()

The built-in bin() function converts an integer number into its binary representation, returning it as a string. The resulting string is prefixed with 0b to indicate that it’s a binary number:

Python
>>> bin(42)
'0b101010'

bin() Signature

Python Syntax
bin(x)

Arguments

Argument Description
x An integer or an object implementing an .__index__() method that returns an integer

Return Value

  • A string representing the binary equivalent of the given integer prefixed with "0b"

bin() Examples

With a positive integer as an argument:

Python
>>> bin(15)
'0b1111'

With a negative integer as an argument:

Python
>>> bin(-10)
'-0b1010'

With an object implementing the .__index__() method:

Python
>>> class Number:
...     def __init__(self, value):
...         self.value = value
...     def __index__(self):
...         return self.value
...

>>> number = Number(10)
>>> bin(number)
'0b1010'

bin() Common Use Cases

The most common use cases for the bin() function include:

  • Converting integers to their binary representation for bitwise operations
  • Displaying binary numbers in a readable format
  • Debugging binary data and bit manipulation

bin() Real-World Example

Say you need to manipulate colors in hexadecimal and RGB (red, green, blue) formats. We can use bin() to break down this color into its individual red, green, and blue components in binary form:

Python
>>> def rgb_to_bin(rgb_color):
...     red = bin(rgb_color[0])[2:].zfill(8)
...     green = bin(rgb_color[1])[2:].zfill(8)
...     blue = bin(rgb_color[2])[2:].zfill(8)
...     return red, green, blue
...

>>> rgb_color = (255, 0, 0)
>>> binary_color = rgb_to_bin(rgb_color)
>>> binary_color
('11111111', '00000000', '00000000')

The rgb_to_bin() function converts each of the RGB components into their binary representations using the bin() function.

Tutorial

Bitwise Operators in Python

In this tutorial, you'll learn how to use Python's bitwise operators to manipulate individual bits of data at the most granular level. With the help of hands-on examples, you'll see how you can apply bitmasks and overload bitwise operators to control binary data in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader