tags:

views:

226

answers:

6

I've seen this a couple of times, but it seems to me that using the bitwise shift left hinders readability. Why is it used? Is it faster than just multiplying by 2?

+14  A: 

It is faster on old compilers that don't optimize the * 2 calls by emitting a left shift instruction. That optimization is really easy to detect and any decent compiler already does.

If it affects readability, then don't use it. Always write your code in the most clear and concise fashion first, then if you have speed problems go back and profile and do hand optimizations.

Edison Gustavo Muenz
+1  A: 

For some architectures, bit shifting is faster than multiplying. However, any compiler worth its salt will optimize *2 (or any multiplication by a power of 2) to a left bit shift (when a bit shift would be faster).

Mark Rushakoff
A: 

If you are using a old C compiler, it is preferrable to use bitwise. For readability you can comment you code though.

Kalpak
+17  A: 

You should use * when you are multiplying, and << when you are bit shifting. They are mathematically equivalent, but have different semantic meanings. If you are building a flag field, for example, use bit shifting. If you are calculating a total, use multiplication.

recursive
very good point. If you want to move the bits one place to the left, use `<< 1`. if you want to make a number twice as large, use `* 2`. Same effect, but much clearer what you're using the number for.
nickf
+1. Express your **intent** in your code, don't try to second guess the compiler (unless you've profiled the code and determined that doing it one way or the other makes a significant difference in the performance).
Grant Wagner
+4  A: 

It's used when you're concerned with the individual bits of the data you're working with. For example, if you want to set the upper byte of a word to 0x9A, you would not write

n |= 0x9A * 256

You'd write:

n |= 0x9A << 8

This makes it clearer that you're working with bits, rather than the data they represent.

yjerem
+2  A: 

For readability of values used as bitfields:

enum Flags { UP       = (1<<0),
             DOWN     = (1<<1),
             STRANGE  = (1<<2),
             CHARM    = (1<<3),
             ...

which I think is preferable to either '=1,...,=2,...=4' or '=1,...=2, =2*2,...=2*3' especially if you have 8+ flags.

the_mandrill