Shift operation in Java

xiaoxiao2021-03-06  101

The bit operations in Java include: & | ~ >> << >>>, the previous few are very simple, mainly because the operation is relatively easy to make an error .1. << Logic left shift, right back 0, symbol bit, and other Like the number: X << 1 is generally equivalent to 2X, but may overflow. Overflow range: 230 ~ (231-1) binary representation 010000 ... 000 to 01111 ... 1111, the highest change For 1, it becomes a negative number. Negative: x << 1 is generally equivalent to 2X, or may overflow. Overflow range: -231 ~ - (230 1) binary representation 1000 ... 000 to 101111 ... 1111 The highest shift is turned into 0, becomes a positive number .2. >> Calculation right shift, and the above do not correspond, the left is added to the left, and the left is added to the left 1.x >> 1 It is equivalent to X / 2, the remainder is abandoned, because this is shrinking, so it will not overflow. However, there is a little attention: -1 is -1. The remainder of the addition is positive, 3 >> 1 = 1 The remainder of the abandon is 1. -3 >> 1 = -2 is also 1, not -1. For positive x >> 1 and x / 2 equal to negative numbers x >> 1 and x / 2 do not necessarily equal.

3. >>> Logic right shift, this is to move with the corresponding symbol bit with the <<, to the left to supplement 0 for positive numbers, >>> and >> are the same for negative numbers, and turn right after right shift Number.

You can use Integer.TobinaryString (INT i) to see 01 bits, more intuitive.

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

New Post(0)