tags:

views:

1377

answers:

4

How to multiply a given number by 2 without using arithmetic operators in c language?

+19  A: 

Use 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

kgiannakakis
make me much clear ?
sevugarajan
Read about binary in your own language. 2 is "10" in binary, and three is "11". So in binary, 3 * 2 = 6 is written like this: 11 * 10 = 110 WHICH IS THE SAME AS A LEFT SHIFT.
Peter Wone
"and long numbers" -- what? Isn't the long data type an integer one?
strager
Actually you are right. I mean it works for int and long data types, which are all integers.
kgiannakakis
+6  A: 

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.

Brian Rasmussen
make me much clear ?
sevugarajan
As per the tag, this is a homework assignment.
Matt Olenik
That tag was added after my answer, but even for homework it would be a good idea to point out that this is not the proper way to do multiplication in a high level language.
Brian Rasmussen
+6  A: 

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
Peter Gibson
+5  A: 

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;
}
Alphaneo
Generally, if you're dealing with signed variables, you want to be well aware of what are you doing precisely, and generally should avoid bit manipulations. If I had to multiply using shifts, I'd probably keep the sign bit as a separate char and make sure to put it back in. Or write it in pure assembly and abuse the carry flag.
Daniel Goldberg
Usually -ve numbers are stored 2s compliment in which case shifting should work fine and preserve the sign bit. You still have problems with overflow, but that is the case with straight multiplication also.
Peter Gibson