Which is the better way to divide an integer by 2?

Asked 2 years ago, Updated 2 years ago, 84 views

Which one is better between the two methods below? Please write down the reason, too

int x = 3;
x = x >> 1;
x = x / 2;

c++ c optimization division

2022-09-21 17:38

1 Answers

Write differently depending on what you do

If you're dealing with a variable like a continuous bit, use bitshift If you're dealing with it like a number, you'd better write it

However, the two methods are not exactly the same, so you have to use them carefully. For example -5/2 == -2 -5>>1 == -3 Like.

In principle, bitshift is faster than division Readability is more important.

And some compilers change the division to bitshift.


2022-09-21 17:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.