ZetCode

Python bin function

last modified November 29, 2026 Python 3.15

In this article we show how to use the bin builtin function, which converts an integer to a binary string.

The result starts with 0b and is a valid Python expression: int(bin(n), 2) gives back the number, and the literal 0b101 has the same value as 5.

The other bases are covered in Python oct function and Python hex function. Parsing integers is described in Python int function, formatting in Python format function, and the integer protocol in Python __index__ method.

Positive integers and zero

The prefix marks the base, so the text can be read without knowing where it came from.

basic_bin.py
print(bin(0))
print(bin(1))
print(bin(5))
print(bin(255))
print(bin(1 << 64))

The prefix is lowercase 0b and there are no leading zeros, except for zero itself, which is 0b0.

Python integers have no fixed width, so large values are printed in full. A power of two is a one followed by as many zeros as the exponent.

$ python basic_bin.py
0b0
0b1
0b101
0b11111111
0b10000000000000000000000000000000000000000000000000000000000000000

Negative numbers

bin writes a minus sign in front of the magnitude, so a negative value is not shown in two's complement.

negatives.py
for n in (-1, -5, -255):
    print(f'{n:4} {bin(n)}')

print(bin(-5 & 0xff))
print((-5).to_bytes(1, 'big', signed=True))

Two's complement needs a width, which a plain bin call does not have. The last two lines choose one: masking with 0xff keeps the low eight bits, and to_bytes produces the same bits as a byte string.

The mask result is what a fixed-width register would hold, including the leading ones.

$ python negatives.py
  -1 -0b1
  -5 -0b101
-255 -0b11111111
0b11111011
b'\xfb'

Converting back

The output is accepted by int, which makes the round trip explicit.

roundtrip.py
for text in ('0b101', '-0b101', '101', '0B101'):
    print(text, int(text, 2))

print(int('0b101', 0))
print(0b1010, bin(0b1010))

int(text, 2) accepts the prefix, the sign, and both cases of the b. Base zero lets Python detect the prefix, which also works for hexadecimal and octal text.

The last line shows the same value written in the two directions, as a literal and as a call.

$ python roundtrip.py
0b101 5
-0b101 -5
101 5
0B101 5
5
10 0b1010

Width and separators

bin has no options. Padding and grouping come from the format mini-language.

formatting.py
n = 42

print(bin(n))
print(f'{n:b}')
print(f'{n:#b}')
print(f'{n:08b}')
print(f'{n:#010b}')
print(f'{n:_b}')

The b type prints the digits without a prefix, and # adds it back. A leading zero and a width pad the field, and _ groups the digits.

The width counts the prefix and the digits together, which is why #010b gives eight digits after 0b.

$ python formatting.py
0b101010
101010
0b101010
00101010
0b00101010
10_1010

Counting bits

Two integer methods answer the usual questions about the bits of a number without building a string.

bit_count.py
values = [0, 1, 5, 42, 255, 1024]

for n in values:
    print(f'{n:5} {bin(n):>14} {n.bit_length():2} {n.bit_count():2}')

bit_length returns the number of bits needed to write the value, and bit_count returns the number of ones. The last column matches a count of the '1' characters in the second one.

Since Python 3.10 the count is a method on int; older code counted the characters of bin(n). For negative numbers both methods work on the absolute value.

$ python bit_count.py
    0            0b0  0  0
    1            0b1  1  1
    5          0b101  3  2
   42       0b101010  6  3
  255     0b11111111  8  8
 1024  0b10000000000 11  1

Bit flags

A binary representation makes a set of flags readable, because every flag occupies one position.

flags.py
READ = 0b001
WRITE = 0b010
EXEC = 0b100

permissions = READ | WRITE
print(bin(permissions))
print(bool(permissions & READ), bool(permissions & EXEC))

permissions |= EXEC
print(bin(permissions))

permissions &= ~WRITE
print(bin(permissions))

OR combines flags, AND tests one, and AND with the complement clears it. The binary strings show the current combination directly.

The same numbers printed in decimal would be 3, 7, and 5, which hide the individual bits.

$ python flags.py
0b11
True False
0b111
0b101

Objects with __index__

bin does not require a plain int; it accepts any object with an __index__ method, the protocol for objects that behave as integers.

index_obj.py
from enum import IntEnum


class Register(IntEnum):
    STATUS = 0b0001
    CONTROL = 0b0010
    DATA = 0b0100


class Mask:
    def __init__(self, value):
        self.value = value

    def __index__(self):
        return self.value


print(bin(Register.CONTROL))
print(bin(Mask(12)))
print(bin(True), bin(False))

IntEnum members and bool values qualify because they are integers already; the Mask class qualifies because it implements the protocol.

A class that defines only __int__ is not enough, since bin asks for an index, not a converted value.

$ python index_obj.py
0b10
0b1100
0b1 0b0

Values that cannot be converted

There is no implicit truncation, so a float is rejected even when it holds a whole number.

errors.py
values = [3.0, '5', None]

for value in values:
    try:
        bin(value)
    except TypeError as e:
        print('TypeError:', e)

print(bin(int(3.9)))

Call int or round first when the value comes from a computation or from text; int truncates toward zero, so 3.9 becomes 3.

Strings are not parsed either. The base has to be named explicitly with int(text, 2) as in the earlier section.

$ python errors.py
TypeError: 'float' object cannot be interpreted as an integer
TypeError: 'str' object cannot be interpreted as an integer
TypeError: 'NoneType' object cannot be interpreted as an integer
0b11

Source

Python bin() documentation

Python integer literals

Python int.bit_count()

In this article we have used bin to write integers in base two, to inspect single bits, and to combine flags. For the other bases see Python oct function and Python hex function, and for custom formatting Python format function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.