Using bitwise operators

后端 未结 12 1657
既然无缘
既然无缘 2021-01-06 08:21

I\'ve been studying C# and ran accross some familiar ground from my old work in C++. I never understood the reason for bitwise operators in a real application. I\'ve never u

12条回答
  •  执念已碎
    2021-01-06 08:42

    Left and right shift operators (<< and >>) are often used in performance critical applications which do arithmetic operations and more specifically multiplications and divisions by powers of two.

    For example suppose you had to calculate the mathematical expression 5*2^7. A naive implementation would be:

    int result = 5 * (int)Math.Pow(2, 7);
    

    Using left shift operator you could write:

    int result = 5 << 7;
    

    The second expression will be orders of magnitude faster than the first and yet yielding the same result.

提交回复
热议问题