Junior
How can an integer be multiplied or divided by 2 using bitwise operations?
sobes.tech AI
Answer from AI
To multiply by 2, a left bit shift (<<) is used.
To divide by 2, a right bit shift (>>) is used.
int num = 10;
int multiplied_by_2 = num << 1; // num * 2 = 20
int divided_by_2 = num >> 1; // num / 2 = 5 (for positive numbers)
When dividing a negative number by 2 using a right bit shift (>>), the result depends on the type of shift:
- Logical (unsigned): The vacated bits on the left will be filled with zeros.
- Arithmetic (signed): The vacated bits on the left will be filled with the sign bit value (to preserve the sign).
In C/C++, arithmetic shift is used for signed types. This can lead to unexpected results for odd negative numbers:
int negative_num = -7;
int divided_by_2_signed = negative_num >> 1; // -4 (not -3)
To correctly divide negative numbers by 2 with rounding towards zero when using bit shifts, you can use the following approach:
int negative_num = -7;
int divided_by_2_corrected = (negative_num >= 0) ? (negative_num >> 1) : ((negative_num + 1) >> 1); // -3