Understanding Bitwise Operations
Bitwise operations are fundamental operations that work on individual bits of binary numbers. They are extensively used in computer science, programming, digital electronics, networking (subnet masks), cryptography, and low-level system programming. Understanding these operations is essential for anyone working with computer systems at a fundamental level.
Bitwise Operation Truth Tables
AND Operation
Returns 1 only when both input bits are 1. Used for masking and clearing bits.
OR Operation
Returns 1 when at least one input bit is 1. Used for setting bits.
XOR Operation
Returns 1 when inputs differ. Used for toggling bits and encryption.
NOT Operation
Flips every bit: 0 becomes 1 and 1 becomes 0. Also called one's complement.
Practical Applications
AND Operations
AND operations are commonly used for bit masking -- extracting specific bits from a value. For example, to check if the 3rd bit is set, you AND the value with 00000100 (binary). Network subnet masks use AND to determine network addresses from IP addresses.
OR Operations
OR operations are used for setting specific bits without affecting others. For example, to set the 5th bit, you OR the value with 00010000. This is common in flag registers and permission systems.
XOR Operations
XOR is widely used in cryptography (one-time pad encryption), error detection (checksums), swapping variables without temporary storage, and graphics (toggling pixels). XOR has the unique property that A XOR A = 0 and A XOR 0 = A.
NOT Operations
NOT (bitwise complement) flips all bits. In signed number systems, NOT of a number plus one gives its two's complement (negative). NOT is used in creating bitmasks and computing two's complement for subtraction.
Common Use Cases in Programming
- Flag checking: Use AND with a mask to test if specific bits are set.
- Flag setting: Use OR with a mask to set specific bits.
- Flag toggling: Use XOR with a mask to flip specific bits.
- Flag clearing: Use AND with NOT of a mask to clear specific bits.
- Swapping values: a = a XOR b; b = a XOR b; a = a XOR b;
- Checking parity: XOR all bits together to determine odd or even parity.