Bit operators and shift operations in Java are described in detail

  • 2020-04-01 02:34:22
  • OfStack

One bit operation

There are four bit operations in Java, and their operation rules are as follows:

(1) bitwise and (&) : the two bits are all 1, the result is 1, otherwise it is 0;

(2) bitwise or (|) : if one of the two bits is 1, the result is 1, otherwise it is 0;

(3) inverse by bit (~) : 0 changes to 1, 1 changes to 0;


(4) by bit or (^) : two bits, if the same, the result is 0; If it's different, it's 1;

Note:

(1) the sign bit (the highest bit) in bit operation is also changed;

(2) bit operators and logical operators (logic and &&, logic or ||, logic! (kind of. However, logical operators can only operate on Boolean variables

(that is, the left and right values are Boolean);


Application of binary bit operation


(1) ~ 5 =?

A) the complement of 5 is:

00000000 00000000 00000000 00000101

B) bitwise inversion (~) of 5 is:

11111111 11111111 11111111 11111010


Note: since the high digit is 1(negative), the complement code should be converted to the original code. If the high digit is 0 (positive), you don't have to change the complement to the original code, because the original code, the inverse code, the complement of a positive number are the same.

C) turn the complement of the negative number into the inverse:

11111111 11111111 11111111 11111001


D) convert the negative code to the original code:

10000000 00000000 00000000 00000110


E) convert binary source code to decimal:


10000000 00000000 00000000 00000000110 = 0 * 2^0 + 1 * 2^1 + 1 * 2^2 = 0+2+4 = -6 (highest bit is 1, so negative)


Iii. Shift operation:

There are three shift operators in Java.


(1) arithmetic right shift (> >) : the low position overflow, the sign bit remains unchanged, and the sign bit compensates the high position of the overflow;

For example: a > > B: a is the number to be moved, and b is the number of digits to be moved.


(2) arithmetic left shift (< < ) : the symbol bit remains unchanged, and the low bit complement 0;


(3) logic right shift (> > >) : low overflow, high fill 0; Note: logical shift right (> > >) The sign bit (the highest bit) in

Iv. Points to note:

Bit operation and shift operation, are the use of binary complement code, operation, avoid!


Related articles: