Clever bit operation design and clever operation design
Bitwise operators
| Example |
Name |
Result |
| $ A & $ B |
And (bitwise And) |
Set the bits of $ a and $ B to 1. |
| $ A | $ B |
Or (by bit Or) |
Set any one of $ a and $ B to 1. |
| $ A ^ $ B |
Xor (by bit or) |
Set one of $ a and $ B as 1 and the other as 0 to 1. |
| ~ $ |
Not (bitwise inversion) |
Set the bits 0 in $ a to 1, and vice versa. |
| $ A <$ B |
Shift left (left Shift) |
Move the bits in $ a to the left for $ B (each movement represents "multiplied by 2 "). |
| $ A> $ B |
Shift right (right Shift) |
Move the bits in $ a to the right $ B (each movement indicates "divided by 2 "). |
During our programming career, we occasionally encounter some operators similar to | (bitwise OR), & (bitwise AND), and ^ (bitwise OR, we only understand their general meanings and seldom use them in instances. For example:
E_ERROR = 1;E_COMPILE_ERROR = 64;E_CORE_ERROR = 16;
When we determine whether the value of a variable ($ severity) is one of the above, the first impression will come up with the following method:
if(E_ERROR ==$severity || E_COMPILE_ERROR == $severity || E_USER_ERROR == $severity ){ return TRUE;} else { return FALSE;}
Seriously, we will find that bitwise operations can quickly and skillfully solve this problem:
if(((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR ) & $severity) === $severity){return TRUE;} else {return FALSE;}Decimal: E_ERROR = 1; converted to binary: 1 decimal: E_COMPILE_ERROR = 64; converted to binary: 1000000 decimal: E_CORE_ERROR = 16; converted to binary: 10000 (E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR) the three constants pass the | bit operation to get 1010001 (E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR) & $ severity, that is, 1010001 & $ severity. When $ severity = 1: 1010001 & $ severity = 1, so (1010001 & $ severity) ==$ severity; when $ severity = 1000000: 1010001 & $ severity = 1000000, so (1010001 & $ Severity) ==$ severity; when $ severity = 10000: 1010001 & $ severity = 10000, so (1010001 & $ severity) = $ severity when the value of $ severity is one of the above three constants, the bitwise operation will get the same value as the value of $ severity itself, so this operation is true. We know from the above that bitwise operators can quickly solve our problems, especially in some algorithms, bitwise operators are very common, because our machine language is binary, not 0 is 1, through bitwise operations, you can quickly calculate problems. Of course, we must follow certain principles when defining some variables. The above article only makes everyone understand the truth.