Bit Shifting: Left Shift and Right Shift Operations
Understand left shift and right shift bit operations. Learn logical vs arithmetic shifts, their equivalence to multiplication and division by powers of two.
Detailed Explanation
Bit shifting moves all bits in a binary number to the left or right by a specified number of positions. It is one of the fastest operations a CPU can perform and is foundational to efficient algorithms.
Left shift (<<):
Shifts bits to the left, filling vacated positions with zeros. Each left shift multiplies the value by 2.
00001010 << 1 = 00010100 (10 x 2 = 20)
00001010 << 3 = 01010000 (10 x 8 = 80)
Right shift (>>):
Shifts bits to the right. Each right shift divides by 2 (integer division, truncating the remainder).
00010100 >> 1 = 00001010 (20 / 2 = 10)
00010100 >> 2 = 00000101 (20 / 4 = 5)
Logical vs. arithmetic right shift:
- Logical shift (
>>>in JavaScript): Fills with zeros. Used for unsigned numbers. - Arithmetic shift (
>>): Fills with the sign bit (preserves negative numbers).11110000 >> 2 = 11111100(the leading 1s are preserved).
Performance advantage:
Shifting is much faster than multiplication/division on most CPUs. Multiplying by powers of 2 via shifting is a classic optimization:
n * 4=n << 2n / 8=n >> 3n * 10=(n << 3) + (n << 1)
Practical applications:
- Color channel extraction:
(pixel >> 8) & 0xFFextracts the green channel from a 24-bit RGB value. - Power of 2 calculation:
1 << ncomputes 2 raised to the power n. - Bit field packing: Combine multiple small values into one integer by shifting and OR-ing.
- Fast averaging:
(a + b) >> 1computes the average of two integers (be careful of overflow).
Common pitfalls:
- Shifting by more than the bit width is undefined behavior in C/C++.
- Shifting negative numbers with
>>is implementation-defined in C (though virtually all modern compilers use arithmetic shift). - In JavaScript, all bitwise operations work on 32-bit integers, even though numbers are 64-bit floats.
Use Case
Game engine developers use bit shifting to pack and unpack multiple data fields (position, rotation, flags) into single 32-bit or 64-bit integers for cache-efficient entity systems.
Try It — Number Base Converter
Related Topics
Bitwise Operations: AND, OR, XOR, NOT
Binary Operands → Binary Result
Binary Arithmetic: Addition and Subtraction
Binary (Base 2) → Binary (Base 2)
Two's Complement: Signed Binary Numbers
Binary (Base 2) → Signed Decimal
Convert Binary to Decimal
Binary (Base 2) → Decimal (Base 10)
IEEE 754 Floating Point Binary Representation
Decimal (Floating Point) → Binary (IEEE 754)