HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
betterdividinguseintegerforoptionnumberwhich

Problem

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

Technique 1:

x = x >> 1;


Technique 2:

x = x / 2;


Here x is an integer.

Solution

Use the operation that best describes what you are trying to do.

  • If you are treating the number as a sequence of bits, use bitshift.



  • If you are treating it as a numerical value, use division.



Note that they are not exactly equivalent. They can give different results for negative integers. For example:

-5 / 2  = -2
-5 >> 1 = -3


(ideone)

Code Snippets

-5 / 2  = -2
-5 >> 1 = -3

Context

Stack Overflow Q#10681375, score: 857

Revisions (0)

No revisions yet.