Careful

xiaoxiao2021-03-06  63

In the program, sometimes in order to increase efficiency, it may be used in many places, especially in some frequent operations.

such as:

Suppose the integer X is N times of 2, (n is a non-negative integer). Y is another positive integer.

Then Y / X is equal to Y >> N, Y * X can be equal to Y << n, y% x is equal to Y & (X-1).

In this way, this special multiplication, division, and if the surplus operation is replaced by the bit operation, it improves the efficiency.

But we should be more careful when we are using it. Let's look at the following example:

When Y is a negative number, the situation has changed.

(-16) / 4 is equal to -4; (-16) >> 2 is also equal to -4. But (-17) / 4 is equal to -4, (-17) >> 2 is not equal to -4, but -5. So when the negative number is operated, it should be careful to avoid unexpected errors.

There is also an exceptionally careful symbol priority when bit operation: Look at an example:

(16 >> 2 - 2) and ((16 >> 2) -2) Difference: The former is equal to (16 >> (2-2)) = 16, the latter is equal to 2. So I suggest it in use It is enclosed in parentheses. :)

转载请注明原文地址:https://www.9cbs.com/read-85591.html

New Post(0)