How to do a bitwise NOR Gate in Python (editing python maths to work for me)

后端 未结 2 510
南旧
南旧 2020-12-10 23:12

Say I was to write this:

a=01100001 
b=01100010 
c=01100011 
d=01100100 
e=01100101 

each letter resembles the given numbers now how would

相关标签:
2条回答
  • 2020-12-10 23:56

    You gave us the "truth table" of all possible inputs (thanks for that). And you say that the output should be 1 if both inputs are 0, otherwise the output should be 0. The name of that logical operation is NOR, i.e. the negation of OR.

    Note that your inputs are base 10 numbers, but they appear to represent base 2 numbers, or bitsets. So perhaps the first thing we should do is convert them from their base 10 form to base 2. A simple (but not overly efficient) way would be int(str(a), 2).

    From there, it's just a matter of doing the NOR operation on the numbers. From here: https://wiki.python.org/moin/BitwiseOperators it looks like you can do ~(x|y) (negated OR, bitwise).

    0 讨论(0)
  • 2020-12-10 23:58

    You said:

    What I wish to do is a + b = 10011100

    My solution:

    >>> a=0b01100001
    >>> b=0b01100010
    
    >>> bin((a | b) ^ 0b11111111)
    '0b10011100'
    

    And now, for the explanation:

    You are asking for a NOR bitwise operation (http://en.wikipedia.org/wiki/NOR_gate if it's not obvious):

    r = not (a or b)
    

    Also, you can use De Morgan's law, that says that it's equivalent to:

    r = (not a) and (not b)
    

    In Python:

    >>> bin((a ^ 0b11111111) & (b ^ 0b11111111))
    '0b10011100'
    

    You may also wonder what's that ^ 0b11111111. Well, not a is equivalent to a xor 1 and xor is written ^ in python. I'd suggest you write down the logic table if you are not 100% convinced. So basically, ^ 0b11111111 changes the 0 to 1 and the 1 to 0.

    The bin function gives the binary representation of the number given as a parameter. The 0b at the beginning of a number means that the number is given in base 2 (otherwise it's base 10).

    Edit:

    Initially, my first thought for this problem was:

    bin(~(a|b))
    

    But the result is '-0b1100100'. This is because in Python the number are signed. But it is also possible to get the good result by only keeping the first byte:

    >>> bin(~(a|b) & 0xff)
    '0b10011100'
    

    Edit 2:

    I've just found that OP asked another question in order to better understand my answer. So, if you wonder why I used a XOR to do the NOT, see a good explanation here: https://stackoverflow.com/a/19203069/1787973

    0 讨论(0)
提交回复
热议问题