Data Representation & Number Systems

a bitwise operation

A bitwise operation works on a number not as a single quantity but as a row of independent bits, applying a simple logic rule to each bit position separately. Imagine two rows of light switches lined up; a bitwise operation compares switch 1 with switch 1, switch 2 with switch 2, and so on, deciding each output switch on its own. This is different from ordinary arithmetic, where a carry from one column can ripple into the next — here each column is entirely independent.

There are four everyday operations. AND gives a 1 only where both inputs are 1, so it is used to mask — keep some bits, force others to 0. OR gives a 1 where either input is 1, so it is used to set bits on. XOR (exclusive or) gives a 1 only where the two inputs differ, which makes it perfect for toggling bits and for spotting differences. NOT flips every bit (the complement). For example, with a = 0b1100 and b = 0b1010: a AND b = 0b1000, a OR b = 0b1110, a XOR b = 0b0110. These map directly onto the logic gates the chip is built from, so they are extremely fast.

Bitwise operations are the everyday tools for packing several yes/no flags into one integer and then reading or changing them: AND with a mask to test a flag, OR to set it, XOR to flip it, AND with the inverted mask to clear it. A common confusion to avoid: bitwise AND (written & in C-like languages) is not the same as logical AND (written &&). Bitwise AND combines two numbers bit by bit and yields a number; logical AND combines two true/false conditions and yields a single true or false. Mixing them up is a classic beginner bug.

With a = 0b1100 (12) and b = 0b1010 (10): a AND b = 0b1000 (8), a OR b = 0b1110 (14), a XOR b = 0b0110 (6), NOT a (in 4 bits) = 0b0011 (3). To clear the lowest bit of any value x, compute x AND 0b...1110.

AND masks, OR sets, XOR toggles, NOT flips — each acts on bit positions independently.

Do not confuse bitwise AND (&) with logical AND (&&): the first combines two numbers bit by bit, the second combines two true/false conditions. Swapping them is a notorious beginner bug.

Also called
bit operationsAND OR XOR NOT逐位元運算