The concept and use of bitwise operators

Logical Operators

&& : logical and, all true is true.
If the first operand is false, it is definitely false, and the second operand is not judged.
|| : logical OR, true is true.
If the first operand is true, it must be false, and the second operand is not judged.
! : Logical negation.
Used to reverse the logic state of the operand. For example, true is false after being negated.

Bit operator:

The operand exists in the form of complement in the computer, and the int is 4 bytes (32) bits.
Negation: ~ Invert
each bit of the operand in binary form, that is, 0 becomes 1, and 1 becomes 0. example

  • 8 (ie 0…000 1000), the true value after inversion is -9 (the complement is: 1111…1111 0111)

And: &
All 1 is 1. For the two operands involved in the operation, the corresponding binary bits are ANDed. example:

  • 5&11 is 0101&1011, the result is 1
  • 1&-1 is (1111&1111, the result is -1
  • 1&1 is (1111&0001, the result is 1

Or:|If
there is 1, then it is 1. Example:

  • 5|11 is (0101|1011), the result is 15

XOR: ^ The
same is 0, and the difference is 1. example:

  • 5^11 is (0101^1011), the result is 14

Reserve the right shift of the sign bit: >> Shift
all the binary bits of an operand several bits to the right, the low bit is discarded, and the left vacant is filled with the sign bit . example:

  • 5>>1 is 2
  • 10>>n is equivalent to 10/(2^n), the result is truncated to decimal places
  • -1 how many bits shifted to the right is still -1

The right shift of the sign bit is not reserved: >>>
All binary bits of an operand are shifted right by several bits, the low bit is discarded, and the vacant on the left is filled with 0 . example:

  • 5>>>1 is 2
  • -9>>>1, the result is 2147483643 (01111111 11111111 11111111 11111011)

Reserve the left shift of the sign bit: << shifts
all the binary bits of an operand by several bits to the left, discards the overflowed number, and fills the vacant on the right with 0 . example:

  • 5<<1为10

application:

Determine parity

The last bit of the odd binary number must be 1; the last bit of the even binary number must not be 1;
0x means hexadecimal, 0x1 means 0x00000000 00000000 00000000 00000001
operand & 0x1 , and the result is an odd number when it is 1. (High bit operation efficiency)

Surplus

a% 2^n = a & (2n-1)
For example: 14%8=1110 & 0111 = 0110, which is 6

hash

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41571459/article/details/113983791