How to Convert Decimal Numbers to Binary in Python

To convert a decimal number to binary in Python, use bin(n), which returns a string like '0b10011100', or format(n, "b") and f"{n:b}" for the digits without the 0b prefix. Add a width such as 08b to pad with zeros:

bin(156)          # '0b10011100'
f"{156:b}"        # '10011100'
f"{5:08b}"        # '00000101'

Binary strings are easy to get subtly wrong, so every value here was printed by Python 3.12.5, and the screenshots come from those runs.

You’ll see the built-in conversions, the divide-by-2 method you’d do on paper, negative numbers in two’s complement, decimal fractions, and IP addresses in binary.

Convert decimal to binary with bin(), format() and f-strings

All three use the same algorithm; they differ only in the prefix and formatting options:

n = 156

print(bin(n))            # with the 0b prefix
print(bin(n)[2:])        # prefix sliced off
print(format(n, "b"))    # no prefix
print(f"{n:b}")          # same thing in an f-string
print(f"{n:#b}")         # '#' adds the prefix back
print(f"{5:08b}")        # pad to 8 bits
print(f"{48879:_b}")     # underscore every 4 digits
print(int("10011100", 2))  # and back to decimal

Output:

0b10011100
10011100
10011100
10011100
0b10011100
00000101
1011_1110_1110_1111
156
Command Prompt output of Python converting 156 to binary with bin, format and f-strings, including padding and underscores
156 prints as 10011100 with and without the 0b prefix, 5 pads to 00000101, and int(…, 2) turns it back into 156.

I use f-strings for display because padding and grouping come free. For every detail of the built-in itself, see my Python bin() function guide.

Convert decimal to binary without bin() (divide by 2)

The manual method divides by 2 and writes down each remainder; reading the remainders bottom to top gives the binary number. Here’s the table and a function that does it:

def to_binary(n: int) -> str:
    if n == 0:
        return "0"
    bits = []
    while n > 0:
        n, remainder = divmod(n, 2)
        bits.append(str(remainder))
    return "".join(reversed(bits))

n = 156
print(f"{'n':>4} {'n // 2':>7} {'n % 2':>6}")
while n > 0:
    print(f"{n:>4} {n // 2:>7} {n % 2:>6}")
    n //= 2

for value in (156, 0, 1, 255, 1024):
    print(f"{value:>5} -> {to_binary(value):>12}  matches format(): {to_binary(value) == format(value, 'b')}")

Output:

   n  n // 2  n % 2
 156      78      0
  78      39      0
  39      19      1
  19       9      1
   9       4      1
   4       2      0
   2       1      0
   1       0      1
  156 ->     10011100  matches format(): True
    0 ->            0  matches format(): True
    1 ->            1  matches format(): True
  255 ->     11111111  matches format(): True
 1024 ->  10000000000  matches format(): True
Command Prompt output of the divide-by-2 method converting 156 to binary with a table of quotients and remainders
The remainder column read from the bottom up gives 10011100, and the function matches format() for every test value.

divmod() returns the quotient and remainder together. Going the other way, from bits to a number, is covered in converting binary to decimal in Python.

How do I convert a negative number to binary in Python?

bin() just puts a minus sign in front. Hardware uses two’s complement, so mask the value to a fixed bit width with &:

n = -10
print(bin(n))                      # Python shows a minus sign, not two's complement

for bits in (8, 16):
    mask = (1 << bits) - 1
    print(f"{bits}-bit two's complement:", format(n & mask, f"0{bits}b"))

print(f"{-10 & 0xFF:08b} -> back to int:", int("11110110", 2) - 256)

Output:

-0b1010
8-bit two's complement: 11110110
16-bit two's complement: 1111111111110110
11110110 -> back to int: -10
Command Prompt output of Python converting -10 to binary as 8-bit and 16-bit two's complement with a bit mask
bin(-10) prints -0b1010, while the 8-bit mask gives 11110110 and the 16-bit mask pads the leading ones.

Subtracting 2bits turns the pattern back into the negative number. If you’re working with raw bit strings, see converting a string of 1s and 0s to binary.

Convert a decimal fraction to binary

For the part after the point, multiply by 2 instead of dividing: each whole-number part is the next bit. Some fractions end, and others repeat forever:

def frac_to_binary(x: float, max_bits: int = 20) -> str:
    bits = []
    while x and len(bits) < max_bits:
        x *= 2
        bit = int(x)
        bits.append(str(bit))
        x -= bit
    return "0." + "".join(bits) + ("..." if x else "")

print(0.625, "->", frac_to_binary(0.625))   # exact
print(0.1, "->", frac_to_binary(0.1))       # repeats forever
print(0.1 + 0.2 == 0.3, 0.1 + 0.2)
print((0.625).hex(), (0.1).hex())

Output:

0.625 -> 0.101
0.1 -> 0.00011001100110011001...
False 0.30000000000000004
0x1.4000000000000p-1 0x1.999999999999ap-4

0.625 is exactly 0.101, but 0.1 never ends in binary. That’s why 0.1 + 0.2 isn’t exactly 0.3. float.hex() shows the stored bits in hexadecimal.

When you need exact money values, round for display; my guide to rounding numbers to 2 decimal places in Python shows how.

Convert an IP address and subnet mask to binary

Network engineers do this every day. Pad each octet to 8 bits, or let the ipaddress module turn the whole address into one integer:

import ipaddress

ip = "192.168.10.25"
print(".".join(f"{int(octet):08b}" for octet in ip.split(".")))
print(f"{int(ipaddress.IPv4Address(ip)):032b}")

net = ipaddress.IPv4Network("10.20.0.0/22")
mask = int(net.netmask)
print(net.netmask, "->", ".".join(f"{b:08b}" for b in net.netmask.packed))
print("1 bits in mask:", mask.bit_count(), "| hosts:", net.num_addresses - 2)

Output:

11000000.10101000.00001010.00011001
11000000101010000000101000011001
255.255.252.0 -> 11111111.11111111.11111100.00000000
1 bits in mask: 22 | hosts: 1022
Command Prompt output of Python converting an IPv4 address and a /22 subnet mask to binary with the ipaddress module
Each octet of 192.168.10.25 appears as 8 bits, and the /22 mask shows 22 ones with 1022 usable hosts.

int.bit_count() (Python 3.10+) counts the 1 bits. For adding binary values, head to adding two binary numbers in Python.

Decimal to binary options compared

CodeResult for 10Notes
bin(10)'0b1010'Prefix included
format(10, "b")'1010'No prefix
f"{10:08b}"'00001010'Fixed width
f"{-10 & 0xFF:08b}"'11110110'8-bit two’s complement (for -10)
int("1010", 2)10Back to decimal

For other number conversions, these are good next reads:

Frequently asked questions

How do I convert decimal to binary in Python?

Use bin(n) for '0b…', or format(n, "b") for just the digits.

How do I remove 0b from bin() output?

Use format(n, "b") or f"{n:b}", or slice with bin(n)[2:] for non-negative numbers.

How do I get 8-bit binary in Python?

Use f"{n:08b}", which pads with leading zeros to 8 digits.

How do I show a negative number in two’s complement?

Mask it: format(n & 0xFF, "08b") for 8 bits, or 0xFFFF for 16 bits.

Can I convert a decimal without using bin()?

Yes. Repeatedly divide by 2 with divmod(), collect the remainders and reverse them.

Where is the ‘b’ format code documented?

See the format specification mini-language in the Python docs.