How to make a bitwise NOR gate

后端 未结 3 394
遥遥无期
遥遥无期 2020-12-20 06:07

I\'m trying to understand the code from an answer I received earlier today:

a=0b01100001
b=0b01100010

bin((a ^ 0b11111111) & (b ^ 0b11111111))
         


        
3条回答
  •  死守一世寂寞
    2020-12-20 06:36

    a ^ 0b11111111      #exclusive or's each bit in a with 1, inverting each bit
    
    >>> a=0b01100001
    >>> bin(a ^ 0b11111111)
    '0b10011110' 
    
    >>> bin((a ^ 0b11111111) & (b ^ 0b11111111))
    '0b10011100'
    

    This is different than using the ~ operator since ~ returns a negative binary result.

    >>> bin(~a & ~b)
    '-0b1100100
    

    The reason is the ~ operator inverts all bits used in representing the number, including the leading 0's that are not typically displayed, resulting in a 2's complement negative result. By using ^ and the 8 bit binary mask, only the first 8 bits are inverted.

提交回复
热议问题