Search code examples
c#unity-game-enginemathcomparisonbit-manipulation

What is the difference between "1 << x" and "pow(2, x)"?


So, while using Unity, there was a point where I had to use bitwise operators. Now, don't get me wrong, I'm fully aware of the usefulness of bitwise operators, and in several cases it cannot be replaced without having to make a bunch of ugly code. The question is more like... What's the difference between a and b, here:

double a = 1 << 3;
double b = Math.Pow(2, 3);

From my understanding of both functions and binary, in both cases, you end up with a 1 in the fourth position, and this equals 8... What prevents anyone from using Math.pow over a bitwise operator? Would it really change something?


Solution

  • In general terms, for most languages:

    The pow function is likely to be less efficient, as it essentially general purpose and can raise any number to any power, so cannot be optimized as easily for special cases.

    The bit shifting will map directly to a processor level operation.

    In some languages, the compiler would see that the operations have a constant result and use that, however if there is a little more complexity, then the optimization may be missed.