Which is better option to use for dividing an integer number by 2?

前端 未结 23 1773
甜味超标
甜味超标 2020-11-27 09:10

Which of the following techniques is the best option for dividing an integer by 2 and why?

Technique 1:

x = x >> 1;

Technique

23条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 09:50

    generaly the right shift divides :

    q = i >> n; is the same as: q = i / 2**n;
    

    this is sometimes used to speed up programs at the cost of clarity. I don't think you should do it . The compiler is smart enough to perform the speedup automatically. This means that putting in a shift gains you nothing at the expense of clarity.

    Take a look at this page from Practical C++ Programming.

提交回复
热议问题