How to convert int to binary string in Python ?

In Python, converting an integer to a binary string can be done using built-in functions and string formatting. Below are detailed methods with examples:

1. Using bin() Function

The bin() function converts an integer to a binary string prefixed with 0b.
Example:

num = 10
binary_str = bin(num)
print(binary_str)  # Output: '0b1010'

Remove the 0b prefix:

binary_str = bin(num)[2:]  # Slice to exclude the first two characters
print(binary_str)  # Output: '1010'

Edge Cases:

  • Zero: bin(0)[2:] returns '0' (avoids empty string).
  • Negative Numbers: bin(-5)[2:] returns '-101' (includes a - sign).

2. Using format() or f-strings

Use the format() method or f-strings with the b format specifier to avoid the 0b prefix.

Example with format():

num = 10
binary_str = format(num, 'b')  # 'b' specifies binary format
print(binary_str)  # Output: '1010'

Example with f-strings (Python 3.6+):

num = 10
binary_str = f"{num:b}"
print(binary_str)  # Output: '1010'

3. Adding Leading Zeros

Specify a minimum width in the format specifier to pad with leading zeros.

Example (8-bit binary):

num = 5
binary_str = format(num, '08b')  # Pad to 8 digits
print(binary_str)  # Output: '00000101'

# Using f-strings:
binary_str = f"{num:08b}"
print(binary_str)  # Output: '00000101'

Note: If the number exceeds the specified width (e.g., num = 256 with 08b), the output will show all required bits (e.g., '100000000').

4. Handling Negative Numbers

Python’s default methods show negative numbers with a - sign. For two’s complement representation, use bitwise operations.

Example (8-bit two’s complement):

num = -5
# Compute two’s complement for 8 bits
binary_str = format(num & 0xFF, '08b')
print(binary_str)  # Output: '11111011'

5. Custom Function for Fixed-Length Binary

For a fixed number of bits (e.g., 16 bits), even for large numbers:

def to_binary(num, bits=8):
    return format(num & (2**bits - 1), f'0{bits}b')

print(to_binary(10, 8))    # Output: '00001010'
print(to_binary(300, 8))   # Output: '00101100' (300 truncated to 8 bits)
print(to_binary(-5, 8))    # Output: '11111011' (two’s complement)

Key Methods Comparison

MethodProsCons
bin()Simple, directIncludes 0b prefix
format()/f-stringsClean, no prefixRequires format specifier
Leading ZerosControl over bit lengthMay truncate large numbers
Two’s ComplementHandles negatives accuratelyRequires manual bit masking

Examples

Basic Conversion:

print(bin(7)[2:])        # '111'
print(format(15, 'b'))   # '1111'
print(f"{255:b}")        # '11111111'

Fixed-Width Output:

print(format(3, '04b'))   # '0011'
print(f"{3:04b}")         # '0011'

Negative Numbers:

print(format(-5, 'b'))     # '-101'
print(to_binary(-5, 8))    # '11111011' (two’s complement)

Summary

  • Use bin()[2:] for quick conversion (includes - for negatives).
  • Use format() or f-strings with b for cleaner output.
  • Specify a width (e.g., 08b) for leading zeros.
  • For two’s complement, use bit masking (e.g., num & 0xFF).

Leave a Reply

Your email address will not be published. Required fields are marked *