What do the & and | operators do? How are they different from && and ||? Swift

后端 未结 3 1915
故里飘歌
故里飘歌 2021-01-24 12:38

I\'ve seen many instances where | or &are used, but I haven\'t understood what they are used for. I know what && and ||<

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-24 13:03

    See the Wikipedia page on Bitwise Operation and the Swift documentation for bitwise operators.

    These are bitwise operators. & is bitwise AND and | is bitwise OR.

    See these examples:

        0011 (decimal 3)
    AND 0010 (decimal 2)
      = 0010 (decimal 2)
    
       0101 (decimal 5)
    OR 0011 (decimal 3)
     = 0111 (decimal 7)
    

    Source: Wikipedia

    The uses of bitwise operators have been discussed before on StackOverflow:

    • practical applications of bitwise operations
    • Using bitwise operations

    A use of bitwise XOR (not in your question, but a cool logic gate anyway) that caught my eye (by @Vilx- here) (I don't know how it works, but the answer was accepted and up-voted 34 times)

    EDIT: If you want to know how it works, there's a nice simple proof over on XOR swap algorithm - Wikipedia

    Swapping two integer variables without an intermediary variable:

    A = A^B // A is now XOR of A and B
    B = A^B // B is now the original A
    A = A^B // A is now the original B
    

    If these don't help, the Wikipedia page I already linked to twice in this post has an Applications section, but they don't really apply to higher-level languages (unless for some reason you want to optimize your arithmetic to use only bitwise operations).

提交回复
热议问题