Python bin() Function: Convert Integers to Binary

When I build small Python automation scripts, I often need to inspect values at the binary level. This happens when I work with permission flags, device status codes, color values, or compact settings stored as a single number. A decimal value like 13 is easy to read, but 0b1101 shows exactly which individual bits are switched on.

Python makes this conversion simple with the built-in bin() function. You do not need to install a module or write your own decimal-to-binary loop.

In this practical Python tutorial, you will learn the bin() function syntax, see useful real-world examples, remove the binary prefix, convert binary back to integers, and avoid common mistakes.

What Is the Python bin() Function?

The Python bin() function converts an integer into a binary string.

Binary is a base-2 number system. It uses only two digits: 0 and 1. Each binary digit is called a bit. Computers use bits internally, so binary becomes useful when you work with low-level data, flags, masks, permissions, or binary files.

Here is the basic syntax:

bin(number)

The number argument must be an integer, or an object that can provide an integer through Python’s __index__() method. In everyday Python scripts, you will normally pass an int.

customer_id = 13

binary_customer_id = bin(customer_id)

print(binary_customer_id)

Output:

0b1101

I executed the above example code and added the screenshot below.

bin() Function Python

The result starts with 0b. Python adds this prefix to show that the string represents a binary number.

For example:

  • 0b1 means decimal 1
  • 0b10 means decimal 2
  • 0b101 means decimal 5
  • 0b1101 means decimal 13

The bin() function is part of Python’s built-in functions, so it works without an import. If you are new to built-in tools, review this guide to Python built-in functions.

Python bin() Function Syntax

The bin() function accepts one required argument:

bin(x)

Here, x is an integer value.

The function returns a string, not an integer. That detail matters when you want to join the result with text, save it to a file, or convert it back to decimal later.

report_number = 42
binary_value = bin(report_number)

print(binary_value)
print(type(binary_value))

Output:

0b101010
<class 'str'>

I executed the above example code and added the screenshot below.

Python bin() Function

In this example, bin(42) returns the text value "0b101010". Python prints it without quotation marks, but it remains a string.

Why Use the Python bin() Function?

Most business scripts do not need binary every day. Still, bin() becomes valuable in a few common situations:

  • Checking which settings are active in a single numeric status code
  • Working with bitwise operators such as &|^~<<, and >>
  • Creating binary representations for debugging
  • Processing hardware, sensors, network protocols, or file formats
  • Learning how computers store numeric values
  • Formatting binary output for a command-line reporting tool

For example, suppose a small monitoring script stores four server alerts in one integer. Each bit represents one alert:

  • Bit 0: Disk space alert
  • Bit 1: CPU alert
  • Bit 2: Memory alert
  • Bit 3: Backup alert

If the status value is 13, its binary form is 1101. That means bits 0, 2, and 3 are active.

server_status = 13

print("Decimal status:", server_status)
print("Binary status:", bin(server_status))

Output:

Decimal status: 13
Binary status: 0b1101

I executed the above example code and added the screenshot below.

bin() Function in Python

This is much easier to inspect than guessing what decimal 13 means in a bit-mask system.

Pro Tip: I always print binary values while debugging bitwise logic. A decimal number hides the individual flags, while bin() immediately shows which bits are on and off.

Python bin() Function With Positive Integers

The most common use of the Python bin() function is converting a positive decimal integer into binary.

invoice_count = 25

print(bin(invoice_count))

Output:

0b11001

Python converts decimal 25 into binary 11001.

Here is another example with several values from a simple daily-report script:

report_counts = [0, 1, 2, 5, 10, 16, 31]

for count in report_counts:
print(f"{count} in binary is {bin(count)}")

Output:

0 in binary is 0b0
1 in binary is 0b1
2 in binary is 0b10
5 in binary is 0b101
10 in binary is 0b1010
16 in binary is 0b10000
31 in binary is 0b11111

This example uses a for loop, which repeats code for each item in a collection. If you want more practice with loops and lists, see how to iterate through a list backward in Python and print lists in Python.

Remove the 0b Prefix From bin() Output

The 0b prefix helps Python developers identify binary text. However, you may not want it in a report, a CSV file, or a user-facing console message.

You can remove the first two characters with string slicing.

daily_total = 45

binary_value = bin(daily_total)
binary_without_prefix = binary_value[2:]

print(binary_without_prefix)

Output:

101101

The expression binary_value[2:] starts at index 2 and keeps every remaining character. Since 0b takes the first two positions, the result contains only the binary digits.

You can also write this in one line:

daily_total = 45

print(bin(daily_total)[2:])

Output:

101101

String slicing is useful in many Python tasks, not just binary formatting. You can learn the same technique in this guide on how to slice lists in Python.

Python bin() Function With Negative Numbers

The Python bin() function also accepts negative integers. Python places the minus sign before the binary prefix.

adjustment = -18

print(bin(adjustment))

Output:

-0b10010

This output means negative decimal 18. Python does not show the full internal two’s-complement representation that a computer may use in memory. It simply shows a minus sign and the binary form of the positive value.

refund_adjustments = [-1, -8, -25]

for adjustment in refund_adjustments:
print(f"{adjustment} becomes {bin(adjustment)}")

Output:

-1 becomes -0b1
-8 becomes -0b1000
-25 becomes -0b11001

If you remove the prefix from a negative result using [2:], you will get the wrong result because the minus sign changes the string positions.

amount = -18

print(bin(amount)[2:])

Output:

b10010

Instead, handle negative values separately.

amount = -18

if amount < 0:
binary_without_prefix = "-" + bin(abs(amount))[2:]
else:
binary_without_prefix = bin(amount)[2:]

print(binary_without_prefix)

Output:

-10010

The abs() function returns the absolute value, which means the value without its sign. The script converts the positive portion, removes 0b, and adds the negative sign back.

Format Binary Values With Python bin()

For quick debugging, bin() works well. For cleaner formatting, Python’s format() function and f-strings give you more control.

Use format() for binary output

The format code "b" tells Python to format a number as binary.

order_number = 73

print(format(order_number, "b"))

Output:

1001001

Unlike bin()format(number, "b") does not include the 0b prefix.

order_number = 73

print("Using bin():", bin(order_number))
print("Using format():", format(order_number, "b"))

Output:

Using bin(): 0b1001001
Using format(): 1001001

Use bin() when you want Python’s standard binary representation. Use format() when you want only digits.

Use an f-string for binary output

An f-string lets you place a formatted value directly inside a message.

permission_code = 21

print(f"Permission code in binary: {permission_code:b}")

Output:

Permission code in binary: 10101

The :b part is a format specifier. It tells Python to display permission_code in binary.

If f-strings are new to you, this related guide shows how to format decimal places in Python using f-strings.

Pad Binary Numbers With Leading Zeros

In real scripts, binary values often need a fixed width. For example, an 8-bit status value should always contain eight digits.

Without padding, Python only returns the digits it needs.

status_code = 9

print(bin(status_code))

Output:

0b1001

To display it as an 8-bit value, use format() with 08b.

status_code = 9

print(format(status_code, "08b"))

Output:

00001001

The 0 means pad with zeros. The 8 means use a total width of eight characters. The b means binary.

Here is a practical example from a warehouse scanner status report:

scanner_statuses = {
"Austin Scanner": 3,
"Denver Scanner": 9,
"Seattle Scanner": 17
}

for scanner_name, status_code in scanner_statuses.items():
binary_status = format(status_code, "08b")
print(f"{scanner_name}: {binary_status}")

Output:

Austin Scanner: 00000011
Denver Scanner: 00001001
Seattle Scanner: 00010001

A dictionary stores values as key-value pairs. In this script, each scanner name acts as a key and each numeric status acts as its value. You can learn more in this article on how to initialize a dictionary in Python.

Pro Tip: In my reporting scripts, I use fixed-width binary values for flags and byte data. Leading zeros make comparisons far easier because every position lines up visually.

Convert a Binary String Back to an Integer

The bin() function converts an integer to binary text. To go the other direction, use Python’s int() function with base 2.

binary_status = "101101"

decimal_status = int(binary_status, 2)

print(decimal_status)

Output:

45

The second argument, 2, tells int() that the input uses base 2.

Python also accepts the 0b prefix during conversion.

binary_status = "0b101101"

decimal_status = int(binary_status, 2)

print(decimal_status)

Output:

text45

This is useful when you read a saved binary string from a text file or accept binary input from a user.

saved_status = "0b11001100"

decimal_status = int(saved_status, 2)

print(f"Saved binary status: {saved_status}")
print(f"Decimal status: {decimal_status}")

Output:

Saved binary status: 0b11001100
Decimal status: 204

For more number-conversion techniques, see how to convert decimal numbers to binary in Python and convert a binary string to an integer in Python.

Use Python bin() With Bitwise Flags

One of the most practical uses of the Python bin() function is debugging bitwise flags.

A bitwise flag stores multiple true-or-false settings inside one integer. Each setting gets one bit:

Bit 0 = Read permission
Bit 1 = Write permission
Bit 2 = Delete permission
Bit 3 = Admin permission

Suppose a user named Emily Carter has read, write, and admin access.

READ = 1        # 0001
WRITE = 2 # 0010
DELETE = 4 # 0100
ADMIN = 8 # 1000

emily_permissions = READ | WRITE | ADMIN

print("Decimal permissions:", emily_permissions)
print("Binary permissions: ", format(emily_permissions, "04b"))

Output:

Decimal permissions: 11
Binary permissions: 1011

The | symbol is the bitwise OR operator. It combines the active permissions into one number.

Next, check whether Emily has delete permission.

READ = 1
WRITE = 2
DELETE = 4
ADMIN = 8

emily_permissions = READ | WRITE | ADMIN

has_delete_permission = emily_permissions & DELETE

print("Has delete permission:", has_delete_permission == DELETE)

Output:

Has delete permission: False

The & symbol is the bitwise AND operator. It checks whether a specific bit is active.

You can make the output more readable by adding a reusable function.

READ = 1
WRITE = 2
DELETE = 4
ADMIN = 8

def show_permissions(permission_code):
print(f"Permission code: {permission_code}")
print(f"Binary code: {format(permission_code, '04b')}")
print(f"Read: {bool(permission_code & READ)}")
print(f"Write: {bool(permission_code & WRITE)}")
print(f"Delete: {bool(permission_code & DELETE)}")
print(f"Admin: {bool(permission_code & ADMIN)}")

emily_permissions = READ | WRITE | ADMIN

show_permissions(emily_permissions)

Output:

Permission code: 11
Binary code: 1011
Read: True
Write: True
Delete: False
Admin: True

This style works well in local utilities, admin scripts, server-side automation, and diagnostic tools. A function groups reusable code under one name. If you need a refresher, learn how to define a function in Python and call a function in Python.

Python bin() Function and Boolean Values

Python treats Boolean values as integers in numeric contexts:

  • True acts like 1
  • False acts like 0

That means bin() accepts them.

is_report_ready = True
is_report_failed = False

print(bin(is_report_ready))
print(bin(is_report_failed))

Output:

0b1
0b0

Although this works, I rarely use bin() directly on Boolean values in production code. The output adds little value unless you are inspecting bits in a compact flag system.

Python bin() Function Errors

The bin() function requires an integer. If you pass a string, float, or list, Python raises a TypeError. A TypeError means an operation received a value of an unsupported type.

report_total = "25"

print(bin(report_total))

Output:

TypeError: 'str' object cannot be interpreted as an integer

Convert a numeric string to an integer first.

report_total = "25"

binary_total = bin(int(report_total))

print(binary_total)

Output:

0b11001

A float also causes an error.

average_sales = 25.5

print(bin(average_sales))

Output:

TypeError: 'float' object cannot be interpreted as an integer

Choose how you want to convert the decimal value before calling bin(). For example, int() removes the fractional part.

average_sales = 25.5

whole_sales = int(average_sales)

print(bin(whole_sales))

Output:

0b11001

Be careful here. int(25.5) becomes 25, not 26. If your script needs rounding, use a deliberate rounding rule first. This guide on the round() function in Python can help.

Build a Small Binary Status Reporter

Let’s combine the Python bin() function with a realistic automation example. Imagine that a local IT status script checks office equipment at a Chicago branch. It receives integer status codes from a monitoring system and displays each code as eight bits.

DEVICE_ONLINE = 1
LOW_BATTERY = 2
NEEDS_SERVICE = 4
SECURITY_ALERT = 8

device_statuses = {
"Chicago Printer": DEVICE_ONLINE,
"Boston Scanner": DEVICE_ONLINE | LOW_BATTERY,
"Phoenix Router": DEVICE_ONLINE | NEEDS_SERVICE | SECURITY_ALERT
}

def get_status_labels(status_code):
labels = []

if status_code & DEVICE_ONLINE:
labels.append("Online")

if status_code & LOW_BATTERY:
labels.append("Low battery")

if status_code & NEEDS_SERVICE:
labels.append("Needs service")

if status_code & SECURITY_ALERT:
labels.append("Security alert")

return labels

for device_name, status_code in device_statuses.items():
binary_code = format(status_code, "08b")
status_labels = ", ".join(get_status_labels(status_code))

print(f"{device_name}")
print(f" Binary code: {binary_code}")
print(f" Status: {status_labels}")

Output:

Chicago Printer
Binary code: 00000001
Status: Online
Boston Scanner
Binary code: 00000011
Status: Online, Low battery
Phoenix Router
Binary code: 00001101
Status: Online, Needs service, Security alert

The script uses format(status_code, "08b") because a fixed-width display is clearer for status flags. The get_status_labels() function checks each flag with bitwise AND and builds a readable list of active statuses.

This is the sort of tool I use while troubleshooting integrations. The raw decimal value may come from a CSV file, JSON payload, device API, or database field. Binary output turns that unclear number into something you can inspect quickly.

Things to Keep in Mind

  • bin() returns a string: Do not treat its result as a regular integer. Use int(binary_text, 2) when you need to convert binary text back to decimal.
  • Expect the 0b prefix: Python adds 0b to clearly identify binary output. Use [2:] only for non-negative values, or use format(number, "b").
  • Pass integer values: Convert numeric strings with int() before calling bin(). Decide carefully how your script should handle floats.
  • Use fixed-width output for flags: Choose formats such as "08b" or "016b" when you inspect bytes, permissions, or status masks.
  • Do not use binary for sensitive storage: Binary formatting does not encrypt data or protect passwords, API keys, or customer information.
  • Name flags clearly: Use constant names such as READWRITE, and ADMIN instead of unexplained values like 12, and 8.

Frequently Asked Questions

What does bin() do in Python?

The Python bin() function converts an integer into a binary string. Python adds the 0b prefix to the returned value, so bin(10) returns 0b1010.

Does Python bin() return a string or integer?

bin() returns a string. For example, type(bin(10)) returns <class 'str'>, so convert it with int(value, 2) if you need a decimal integer again.

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

For a positive integer, use bin(number)[2:]. You can also use format(number, "b"), which returns the binary digits without the prefix.

Can I use bin() with a negative number in Python?

Yes. Python returns the minus sign before the prefix, such as bin(-10), which returns -0b1010. Python does not display the internal two’s-complement memory representation.

Why does bin() give me a TypeError?

bin() only accepts integers. Convert a numeric string with int() first, and decide how to handle a float before calling bin().

How do I add leading zeros to a binary number in Python?

Use format(number, "08b") for an 8-bit binary result. For example, format(5, "08b") returns 00000101.

The Python bin() function gives you a fast and readable way to convert integers into binary strings, especially when debugging flags, permissions, and compact status codes. Start with simple conversions, then use format() and bitwise operators when your script needs fixed-width output or real flag handling. I hope you found this article helpful and can use bin() confidently in your next Python project.

You May Also Like

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.