Boolean operators vs Bitwise operators

前端 未结 9 1352
孤街浪徒
孤街浪徒 2020-11-22 06:34

I am confused as to when I should use Boolean vs bitwise operators

  • and vs &
  • or vs |
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 07:13

    Boolean 'and' vs. Bitwise '&':

    Pseudo-code/Python helped me understand the difference between these:

    def boolAnd(A, B):
        # boolean 'and' returns either A or B
        if A == False:
            return A
        else:
            return B
    
    def bitwiseAnd(A , B):
        # binary representation (e.g. 9 is '1001', 1 is '0001', etc.)
    
        binA = binary(A)
        binB = binary(B)
    
    
    
        # perform boolean 'and' on each pair of binaries in (A, B)
        # then return the result:
        # equivalent to: return ''.join([x*y for (x,y) in zip(binA, binB)])
    
        # assuming binA and binB are the same length
        result = []
        for i in range(len(binA)):
          compar = boolAnd(binA[i], binB[i]) 
          result.append(compar)
    
        # we want to return a string of 1s and 0s, not a list
    
        return ''.join(result)
    

提交回复
热议问题