Bit Operations:#
Before learning about bit operations, you need to understand how to convert decimal to binary and binary to decimal. Here is a simple calculation method: To convert from right to left, multiply each number in binary by the corresponding power of 2. For the decimal point, go from left to right.
- For example: How to convert binary to decimal
So the general formula can be summarized as: - For example: How to convert decimal to binary
To convert decimal integers to binary integers, use the method of dividing by 2 and taking the remainder, and arrange them in reverse order. The specific method is: Divide the decimal integer by 2, and you will get a quotient and a remainder. Then divide the quotient by 2 again, and you will get another quotient and remainder. Repeat this process until the quotient is less than 1. Then, take the remainders obtained earlier as the least significant bits of the binary number, and arrange the later remainders as the most significant bits of the binary number. For example: 255=(11111111)B
Left Shift <<:#
10 << 1; //-> 10 in binary is 1010, shifting left by 1 equals 10100, then convert back to decimal to get 20
Right Shift >>:#
13 >> 1; // -> Decimal 13 can be seen as 12+1, 12 in binary is 1100, shifting right by 1 equals 110, then convert back to decimal to get
Bitwise Operations:#
Bitwise AND:#
The result is 1 only if each bit is 1, otherwise it is 0
10 & 8; // -> 1010 & 1000 == 1000 -> 8
Bitwise OR:#
The result is 1 if at least one bit is 1, otherwise it is 0
10 | 8; // -> 1010 | 1000 == 1010 -> 10
Bitwise XOR:#
The result is 1 only if each bit is different, otherwise it is 0
15 ^ 5; // -> 1111 ^ 0101 == 1010 -> 10