Decimal notation uses ten digit symbols; binary uses two, 0 and 1. Each position is worth twice the position to its right. A binary digit is called a bit.
place value: 8 4 2 1
bits: 1 0 1 1
contribution: 8 0 2 1 = 11
The prefix 0b marks a binary integer literal. Leading zeroes after the prefix can make columns easier to see without changing the value. Python normally prints an integer in decimal; bin gives a binary string. A string containing binary digits is text until converted with int(text, 2).
print(0b1011)
print(bin(11))
print(int("1011", 2))
11
0b1011
11
Invalid binary digits such as "102" cause int(..., 2) to raise ValueError.
Combining and selecting bits
Bitwise | sets a result bit when either input has that bit set. Bitwise & sets it only when both inputs have it set. They work on integers, column by column; they are different from the Boolean operators or and and.
0101 0101
| 1010 & 0010
---- ----
1111 0000
A mask is a number used to select specific bits. Here each bit represents a separate option; combining the masks enables both, and & isolates the requested option.
read = 0b0001
write = 0b0100
permissions = read | write
print(bin(permissions))
print((permissions & write) == write)
print((permissions & 0b0010) != 0)
0b101
True
False
bin omits unnecessary leading zeroes. The equality test checks that every bit in write is present; a nonzero test checks whether at least one bit in a mask is present. These examples use nonnegative integers. Real authorization requires more than storing bits: the application must enforce its rules at the appropriate boundaries.