9618 · 4.3
Bit manipulation
Bit manipulation is the art of directly altering the individual 1s and 0s that make up data in a computer. This gives programmers fine-grained control for maximum efficiency and is crucial for tasks like graphics, networking, and systems programming.
Need to know
What you need to know
- **Logical Shift Left (LSL):** All bits shift left. The most significant bit (MSB) is discarded. The least significant bit (LSB) position is filled with a 0. Effect: multiplication by $2^n$ for $n$ shifts.
- **Logical Shift Right (LSR):** All bits shift right. The least significant bit (LSB) is discarded. The most significant bit (MSB) position is filled with a 0. Effect: integer division by $2^n$ for $n$ shifts.
Explanation
Controlling the Code's DNA
- Logical shifts move all bits left or right, filling vacant spots with zeros. This is a fast way to multiply or perform integer division by powers of 2.
- An AND mask is used to clear bits or check if a bit is set. By ANDing a value with a mask, only the bits that are '1' in both the value and the mask remain '1'.
- An OR mask is used to set bits to '1', while an XOR mask is used to toggle (flip) bits. These are essential for managing status flags or setting permissions.
- For signed integers in two's complement, an Arithmetic Shift Right (ASR) is used. It preserves the sign bit to maintain the number's positivity or negativity during division.