How to multiply a given number by 2 without using arithmetic operators in c language?
views:
1377answers:
4Use bit wise << operator:
x = x << 1;
This works for integer and long numbers (not floating point numbers).
It basically shifts the binary contents one position to the left, which is equivalent to multiplying by 2
Left shift.
But why would you want to do that? Leave that kind of optimization to the compiler.
List of operators and plenty of examples on wikipedia.
Just to extend on kgiannakakis post:
The shift operator <<
works because it shifts at the binary level - effectively in base 2. Just as moving a number by one place to the left in decimal (base 10) is the same as multiplying by 10. For example:
23 (move to left one digit) = 230 = 23 * 10
For the example (using the prefix 0b to represent binary numbers):
3 * 2 = 6
0b11 << 1 = 0b110
Shifting by other numbers is equivalent to multiplying by 2 'n' times, or multiplying by 2 to the nth power (2^n)
3 * 8 = 3 * 2^3 = 24
0b11 * 8 = 0b11 << 3 = 0b11000 (note the trailing zeros)
And an example in decimal to finish it off:
23 (move to left 3 places) = 23 * 1000 = 23 * 10^3 = 23000
Caution: Shifting might not work for signed variables,
int x;
int tmp;
if (x < 0) {
tmp = -x;
tmp = tmp << 1;
x = -tmp;
}
else {
x = x << 1;
}