The built-in bin() function converts an integer number to a binary string prefixed with "0b". It is essential for bitwise operations, low-level data protocol encoding, network subnet masks, and debugging binary flags.
Inverse Operation: To convert a binary string back into a decimal integer, use the constructor int(binary_str, 2).
The bin() function accepts a single parameter:
bin(x)
| Parameter | Type | Description |
|---|---|---|
x |
int or object defining __index__() |
The integer to convert into a base-2 binary string. Must be an integer or define an __index__() method that returns an integer. |
Return Value: Returns a string (str) starting with "0b" followed by the binary digits (0 and 1) representing the value. For negative integers, the string starts with "-0b".
When passed a non-negative integer, bin() converts the base-10 value into its binary equivalent prefixed with 0b:
num1 = 5
num2 = 47
num3 = 1024
print(bin(num1)) # 5 in binary
print(bin(num2)) # 47 in binary
print(bin(num3)) # 1024 in binary
0b101
0b101111
0b10000000000
Often in applications such as network formatting or protocol encoding, you need clean binary digits without the "0b" prefix. There are three idiomatic ways to achieve this:
[2:])val = 47
clean_bin = bin(val)[2:]
print(clean_bin) # Output: 101111
format() FunctionPassing format specifier 'b' to format() outputs the binary representation without any prefix:
val = 47
print(format(val, 'b')) # Output: 101111
# If you explicitly want the prefix, use '#b'
print(format(val, '#b')) # Output: 0b101111
val = 47
print(f"{val:b}") # Output: 101111
print(f"{val:#b}") # Output: 0b101111
In hardware interfaces and networking, numbers are often displayed in fixed widths such as 8-bit bytes, 16-bit words, or 32-bit registers. You can pad your binary strings with leading zeros using either str.zfill() or formatting specifiers:
num = 13 # 13 is 1101 in binary
# Method 1: bin() with slice and zfill()
byte_str = bin(num)[2:].zfill(8)
print("8-bit (zfill):", byte_str)
# Method 2: f-string with 08b format specifier
f_byte = f"{num:08b}"
print("8-bit (f-string):", f_byte)
# Method 3: 16-bit word padding
word_16 = f"{num:016b}"
print("16-bit (f-string):", word_16)
8-bit (zfill): 00001101
8-bit (f-string): 00001101
16-bit (f-string): 0000000000001101
Python integers have arbitrary precision (they do not overflow into fixed 32-bit or 64-bit bounds). Because of this, Python represents negative numbers with a simple minus sign followed by 0b and the magnitude:
print(bin(-10)) # Output: -0b1010
bin(-10) show Two's Complement?11110110 for an 8-bit signed byte). Because Python's integers can have infinite bits, there is no fixed number of leading 1s. To obtain the real two's complement representation, mask the number with a fixed bit width.
To convert a negative number into a standard two's complement string for a given bit length (such as 8, 16, or 32 bits), apply a bitwise AND mask with (1 << bits) - 1:
def to_twos_complement(val, bits=8):
# Mask with (2^bits - 1) to constrain to fixed width
mask = (1 << bits) - 1
return bin(val & mask)[2:].zfill(bits)
print(" 10 in 8-bit:", to_twos_complement(10, 8))
print("-10 in 8-bit:", to_twos_complement(-10, 8))
print("-10 in 16-bit:", to_twos_complement(-10, 16))
10 in 8-bit: 00001010
-10 in 8-bit: 11110110
-10 in 16-bit: 1111111111110110
The bin() function is an invaluable tool for inspecting the effects of bitwise operators (bitwise AND, OR, XOR, NOT, and Shifts):
a = 0b1100 # 12 in decimal
b = 0b1010 # 10 in decimal
print("a =", f"{a:04b}")
print("b =", f"{b:04b}")
print("a & b =", f"{(a & b):04b}") # AND: bits both 1
print("a | b =", f"{(a | b):04b}") # OR: either bit 1
print("a ^ b =", f"{(a ^ b):04b}") # XOR: bits differ
print("a << 1 =", f"{(a << 1):05b}") # Left Shift: multiply by 2
print("a >> 1 =", f"{(a >> 1):04b}") # Right Shift: floor divide by 2
a = 1100
b = 1010
a & b = 1000
a | b = 1110
a ^ b = 0110
a << 1 = 11000
a >> 1 = 0110
To reverse a bin() transformation, pass the binary string to the built-in int() function with base 2:
bin_str_with_prefix = "0b101101"
bin_str_raw = "101101"
# Both forms are accepted seamlessly by int(..., 2)
val1 = int(bin_str_with_prefix, 2)
val2 = int(bin_str_raw, 2)
print("From 0b101101:", val1)
print("From 101101: ", val2)
assert val1 == val2 == 45
Passing a floating-point number, string, or complex number directly to bin() raises a TypeError:
try:
bin(3.14)
except TypeError as e:
print("Error:", e)
# Output: Error: 'float' object cannot be interpreted as an integer
However, any user-defined class can be converted by bin() if it defines the special method __index__(self) that returns an integer:
class ByteRegister:
def __init__(self, val):
self.val = val & 0xFF # Keep within 8 bits
def __index__(self):
return self.val
reg = ByteRegister(200)
print("Custom object to binary:", bin(reg))
assert bin(reg) == "0b11001000"
In operating systems (like Linux file permissions rwxr-xr-x), binary bits represent access flags: Read (0b100 = 4), Write (0b010 = 2), and Execute (0b001 = 1). Let's construct a permission manager using bitwise operators and test it with assertions:
# Bitmask constants
PERMISSION_READ = 0b100 # 4
PERMISSION_WRITE = 0b010 # 2
PERMISSION_EXECUTE = 0b001 # 1
def grant_permission(current_mask, new_perm):
return current_mask | new_perm
def revoke_permission(current_mask, perm_to_remove):
return current_mask & ~perm_to_remove
def has_permission(current_mask, check_perm):
return (current_mask & check_perm) == check_perm
# 1. Start with Read-only access
user_perm = PERMISSION_READ
print("Initial:", bin(user_perm))
assert bin(user_perm) == "0b100"
# 2. Grant Write permission
user_perm = grant_permission(user_perm, PERMISSION_WRITE)
print("After Write grant:", bin(user_perm))
assert bin(user_perm) == "0b110" # 6
assert has_permission(user_perm, PERMISSION_READ) is True
assert has_permission(user_perm, PERMISSION_WRITE) is True
assert has_permission(user_perm, PERMISSION_EXECUTE) is False
# 3. Revoke Read permission
user_perm = revoke_permission(user_perm, PERMISSION_READ)
print("After Read revoke:", bin(user_perm))
assert bin(user_perm) == "0b10" # 2
assert has_permission(user_perm, PERMISSION_READ) is False
assert has_permission(user_perm, PERMISSION_WRITE) is True
print("All bitmask validation assertions passed successfully!")
"0x"."0o".&, |, ^, ~, and bit shift operators.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.