Binary shifts are a powerful and efficient way to perform multiplication and division by powers of two. This technique leverages the binary representation of numbers to streamline calculations.
Multiplying a number by 2^n is equivalent to shifting its binary representation n positions to the left. This is because each left shift multiplies the number by 2.
Example:
Multiply 5 by 8 (2^3)
Convert 5 to binary: 101
Code Example:
number = 5
power = 3
result = number << power // equivalent to number * 2^power
Dividing a number by 2^n is equivalent to shifting its binary representation n positions to the right. Each right shift effectively divides the number by 2.
Example:
Divide 24 by 4 (2^2)
Convert 24 to binary: 11000
Code Example:
number = 24
power = 2
result = number >> power // equivalent to number / 2^power
By understanding and leveraging binary shifts, you can optimize your code for multiplication and division by powers of two, resulting in improved performance and efficiency.
Create a customised learning path powered by AI — stay focused, track progress, and earn certificates.
Build Your Learning Path →