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

前端 未结 23 1697
甜味超标
甜味超标 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:31

    Which one is the best option and why for dividing the integer number by 2?

    Depends on what you mean by best.

    If you want your colleagues to hate you, or to make your code hard to read, I'd definitely go with the first option.

    If you want to divide a number by 2, go with the second one.

    The two are not equivalent, they don't behave the same if the number is negative or inside larger expressions - bitshift has lower precedence than + or -, division has higher precedence.

    You should write your code to express what its intent is. If performance is your concern, don't worry, the optimizer does a good job at these sort of micro-optimizations.

    0 讨论(0)
  • 2020-11-27 09:31

    X/Y is a correct one...and " >> " shifting operator..if we want two divide a integer we can use (/) dividend operator. shift operator is used to shift the bits..

    x=x/2; x/=2; we can use like this..

    0 讨论(0)
  • 2020-11-27 09:32

    Obviously, if you are writing your code for the next guy who reads it, go for the clarity of "x/2".

    However, if speed is your goal, try it both ways and time the results. A few months ago I worked on a bitmap convolution routine which involved stepping through an array of integers and dividing each element by 2. I did all kinds of things to optimize it including the old trick of substituting "x>>1" for "x/2".

    When I actually timed both ways I discovered to my surprise that x/2 was faster than x>>1

    This was using Microsoft VS2008 C++ with the default optimizations turned on.

    0 讨论(0)
  • 2020-11-27 09:33

    mod 2, test for = 1. dunno the syntax in c. but this may be fastest.

    0 讨论(0)
  • 2020-11-27 09:34

    In terms of performance. CPU's shift operations are significantly faster than divide op-codes. So dividing by two or multiplying by 2 etc all benefit from shift operations.

    As to the look and feel. As engineers when did we become so attached to cosmetics that even beautiful ladies don't use! :)

    0 讨论(0)
  • 2020-11-27 09:36

    I agree with other answers that you should favor x / 2 because its intent is clearer, and the compiler should optimize it for you.

    However, another reason for preferring x / 2 over x >> 1 is that the behavior of >> is implementation-dependent if x is a signed int and is negative.

    From section 6.5.7, bullet 5 of the ISO C99 standard:

    The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

    0 讨论(0)
提交回复
热议问题