Python 3.11+enumfunction
enum.bin()
flags
The binary form of a number where negatives are shown in two's complement and the first bit is the sign: enum.bin(~10) gives '0b1 0101'.
Syntax
enum.bin(num, max_bits=None)
The built-in bin(-5) prints '-0b101', a minus sign and the magnitude, not the bits that & | ^ ~ operate on. enum.bin shows the bits as bitwise operators see them: the sign bit is separated by a space, and max_bits sets the width. The function lives in enum because it helps debug IntFlag flags, but it works for any int.
Examples
import enum
print(bin(-11)) # → -0b1011
print(enum.bin(10), '|', enum.bin(~10)) # → 0b0 1010 | 0b1 0101
print(enum.bin(5, 8)) # → 0b0 00000101
See also
Open in the full glossarydocs.python.orgReport an inaccuracy