Python Python bin(): Convert Integers to Binary Strings — Syntax, Negative Nu…
page info
name Goposu datetime⏰ 25-10-11 01:38 hit👁️ 14 comment💬 0text

Python bin(): Convert an integer to a binary string
The built-in bin()
function returns the binary representation of an integer as a string, prefixed with 0b
. It supports positive and negative integers (with a leading -0b
) and is commonly used for bitwise operations, flags, masks, and low-level data inspection.
Syntax
bin(x)
Parameter: x
must be an integer (including bool
, since True
and False
are integers).
Returns: A string with a 0b
prefix (e.g., '0b1010'
). Negative integers are represented with a leading minus (e.g., '-0b1010'
).
Quick examples
print(bin(10)) # '0b1010'
print(bin(0)) # '0b0'
print(bin(True)) # '0b1'
print(bin(-5)) # '-0b101'
Remove the 0b prefix
To get the bare binary digits, slice or format:
n = 42
print(bin(n)[2:]) # '101010' (positive only)
print(format(n, 'b')) # '101010' (preferred)
print(f'{n:b}') # '101010' (f-string)
For negatives, handle the sign explicitly:
n = -42
sign = '-' if n < 0 else ''
digits = format(abs(n), 'b')
print(sign + digits) # '-101010'
Common use cases
- Bit flags and masks: Visualize and debug bitwise operations.
- Binary formatting: Display IDs, permissions, or protocol fields.
- Educational purposes: Teach binary arithmetic and representation.
mask = 0b0101
value = 0b1100
print(bin(value & mask)) # '0b0100'
print(format(value | mask, '08b')) # '00001101' (zero-padded to 8 bits)
Padding, grouping, and readability
Use format()
for zero-padding and custom layouts:
n = 13
print(format(n, '08b')) # '00001101' (pad to 8 bits)
print(' '.join(format(n, '016b')[i:i+4] for i in range(0, 16, 4))) # '0000 0000 0000 1101'
Pitfalls and caveats
- Non-integers:
bin()
raisesTypeError
for floats,Decimal
, or strings. - Negative numbers: Python uses a leading
-
with magnitude digits, not two’s-complement within the string. - Byte data: Convert bytes to int first to get binary.
# TypeError for non-int
try:
print(bin(3.5))
except TypeError as e:
print(e)
# Bytes to binary
b = b'\x01\xaf'
n = int.from_bytes(b, byteorder='big')
print(format(n, '016b')) # '0000000110101111'
Comparison with hex() and oct()
- bin(): Binary with
0b
prefix. - hex(): Hexadecimal with
0x
prefix (compact for large values). - oct(): Octal with
0o
prefix.
n = 255
print(bin(n)) # '0b11111111'
print(hex(n)) # '0xFF'
print(oct(n)) # '0o377'
Performance tips
- Formatting API: Prefer
format(x, 'b')
orf'{x:b}'
for padding and bare digits. - Large integers: Python handles arbitrary precision; output length scales with magnitude.
- Streaming/IO: For many values, precompute formatting patterns and reuse to minimize allocations.
FAQ
- How do I get binary without the
0b
prefix? - Use
format(x, 'b')
or slice:bin(x)[2:]
(handle negatives separately). - Can I zero-pad to a fixed width?
- Yes:
format(x, '08b')
pads to 8 bits. Replace08
with your desired width. - How do I represent negative numbers in fixed-width two’s complement?
- Manually mask to a width:
width = 8; print(format(x & ((1 << width) - 1), f'0{width}b'))
.
Related keywords
Python bin, binary string, bitwise operations, format spec, zero padding, two’s complement, int.from_bytes, hex, oct
comment list 0
There are no registered comments.