Is there any advantage to using "<< 1" instead of "* 2"?

I have seen this a couple of times, but it seems to me that using the bitwise shift leaves much to be desired. Why is it used? Is it faster than just multiplying by 2?

+6
source share
6 answers

On older compilers, calls * 2 are not optimized faster, emitting a left shift instruction. This optimization is really easy to spot, and any decent compiler already does.

If this affects readability, then do not use it. Always write your code first in the clearest and most concise way, and then if you have speed problems, go back and profile and do manual optimization.

+17
source

You must use * when multiplying, and <<when โ€‹โ€‹you shift the bit. They are mathematically equivalent, but have different semantic meanings. For example, if you create a flag field, use a bit offset. If you are calculating the total, use multiplication.

+22
source

Used when it comes to individual bits of data that you are working with. For example, if you want to set the top byte of a word to 0x9A , you will not write

 n |= 0x9A * 256 

You must write:

 n |= 0x9A << 8 

This allows you to clarify that you are working with bits, and not with the data that they represent.

+6
source

For some architectures, bit shifting is faster than multiplication. However, any compiler that deserves its salt will optimize * 2 (or any multiplication by 2) by left-shift (when the shift bit is faster).

+2
source

For readability of values โ€‹โ€‹used as bit fields:

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

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

+2
source

If you are using an older C compiler, we recommend using bitwise. For readability, you can comment on the code.

+1
source