@[TOC] (table of contents)
Overview of Bit Operations
Bit operations are operations based on the binary representation of integers. Since the internal data of the computer is stored in binary, bit operations are quite fast. There are 6 basic bit operations, namely bitwise and, bitwise or, bitwise exclusive or, bitwise inversion, left shift and right shift
AND, OR, EXCLUSIVE OR
These three are operations between two numbers, so they are put together here
Note: 1: Here we need to distinguish the difference between logical and and bitwise and logical or and bitwise or.
2: The inverse operation of the XOR operation is itself, that is to say, the same number is XORed twice, and the final result remains unchanged. For example, a^b^b = a
Related examples:
5 = 101 (binary) 6 = (110)
5&6 = 100 (binary) = 4
5|6 = 111 (binary) = 7
5^6 = 011 (binary) = 3
reconciliation
Inversion is a bit operation on a number n, that is, unary operation
There is no default mathematical symbol for negation, and the corresponding operator is ~. Its function is to invert all the sums in the two's complement code (become, become). The sign bit of a signed integer is also negated in the ~ operation.
Note: Complement: In binary representation, the complement of an integer and 0 is itself, and the complement of a negative number is to invert the corresponding positive number and add one
example:
5 = (000000101) binary
-5=(11111010) binary
-5's complement = (11111011) binary
~(-5) = (00000100) binary = 4
Shift left and right
n<< i means the value obtained by shifting the binary of n to the left by i bits
n>>i represents the value obtained by shifting the binary of n to the right by i bits
11= (00001011) binary
11 << 3 = (01011000) binary = 88
11 >> 2 = (00000010) binary = 2
Note: If any operand in the shift operation is negative or the right operand is greater than or equal to the number of bits in the left operation, these behaviors are undefined
For example: a<<-1 ,a>>32