Bitwise AND &, Bitwise OR |, Bitwise XOR^

1. Bitwise AND operator

  • The two data participating in the operation are subjected to the bitwise AND operation according to the binary bits.

          Example: 3&5

         First convert the two data into binary numbers, and then perform the bitwise AND operation, the result is 1 if the same is 1, and the result is 0 in other cases ;

          That is: 11&101=001 result is 1

Special reminder: Negative numbers participate in the bitwise AND operation in complement form .

  • Special uses of bit AND operations:

       1. Clear (bit AND operation of a unit with 0 results in zero)

       2. Take the specified bits in a number (for example, take the lower four bits of X=1010 1101 and X&00001111 will get 0000 1101).

 3. Judging parity: any number and 1 take the bitwise AND, the result is 1 is an odd number

2. Bitwise OR operator

  • For the two data participating in the operation, perform the bitwise OR operation according to the binary bits.
    For example: 3 | 5
    first convert the two data into binary numbers, and then perform the bitwise OR operation. As long as one of them is 1, the result is 1, otherwise the result is 0 ;
    That is: 11&101=111 results in 7

Special reminder: Negative numbers participate in bitwise OR operation in complement form .

  • Special purpose of bit-OR operation: It
    is often used to set certain positions of data to 1 ( for example, set the fourth position of X=1010 1010 to 1, then set X |0000 1111 to get 1010 1111 ).

3. Bitwise XOR Operator

  • 参加运算的两个数据,按二进制位进行位异或运算
    例如:3^5
    先将两个数据转化为二进制数,然后进行按位异或运算,只要位不同结果为1,不然结果为0
    即:11^101=110结果为6
  • 异或运算的特殊用途:
    1.使特定位翻转找一个数,对应X要翻转的各位,该数的对应位为1,其余位为零,此数与X对应位异或即可。
    例:X=10101110,使X低4位翻转,用X ^0000 1111 = 1010 0001即可得到。
    2.与0异或得到原值
    例:X=10101110,用X^0=10101110

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326073249&siteId=291194637