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

后端 未结 3 1902
故里飘歌
故里飘歌 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 12:57

    & and | are bitwise operators that is they compare the bit representation(binary value).

    `&` -bitwise AND operator
    `|` -bitwise OR operator
    

    && and || are used to compare the actual values in case of primitives like int,double,etc. and the address in case of objects.They are called logical operators.

     1. Lets go to an example to make it simpler (bitwise operator):
    
    
    
        int p=9; int q=10;
        //binary representation of 9 and 10 are 1001 and 1010 respectively.
    
    • Now, p & q returns a one in each bit position for which the corresponding bits of both operands are ones.

    • p|q returns a one in each bit position for which the corresponding bits of either or both operands are ones.

       2.An example for logical operators.
       int p=9; int q=10;
      
    • p>0 && q>0 returns true since p and q are both greater than 0(since the conditions on either side of the operator is true).

    • p>0 || q<0 returns true since at least one condition is true(here,p is greater than 0).

    I hope that this has helped you to understand the difference between bitwise and logical operators.

提交回复
热议问题