Skip to content Skip to sidebar Skip to footer

How To Make A Bitwise Nor Gate

I'm trying to understand the code from an answer I received earlier today: a=0b01100001 b=0b01100010 bin((a ^ 0b11111111) & (b ^ 0b11111111)) This is my understanding: bin m

Solution 1:

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.

Solution 2:

Starting with the original answer, which explains how a NOR gate can be implemented using AND and NOT:

You are asking for a NOR bitwise operation:

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)

The poster than translates that pseudo-code into the Python you posted. For some reason he used ^ 0b11111111 to do a binary NOT, rather than simply ~, which is what I would have chosen. If we switch (a ^ 0b11111111) to the simpler ~ then we get:

bin(~a & ~b)

That expression is how you write "(not a) and (not b)" in Python. ~ means NOT and & means AND.

A binary NOT flips all of the bits in a number. 0 becomes 1 and 1 becomes 0. The direct way to do that is with ~. An indirect way to flip all the bits in a number is to XOR it with all 1 bits. That has the same effect, it's just longer to write.

Or actually, to be more precise, it has almost the same effect. ^ 0b11111111 flips the first eight bits of the number because there are eight 1's. Whereas ~ flips all of the bits. If you're interested in only the first 8 bits then you can add & 0b11111111, which truncates the results to 8 bits:

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

In my opinion this is better than the mysterious ^ 0b11111111.

Solution 3:

The ^ is the XOR operator. XOR means Exclusive OR. One of the operand to ^ is a sequence of ones. This essentially means every bit in the other operand (viz., either a or b) will be flipped. Once the two individual XOR operations are done, their results are OR-ed.

Looking outside of bits, and bitwise operations, if you see it from the realm of logic operations, the code is in essence doing (! A ) ^ (! B) which per DeMorgan's law is identically the same as ! (A v B) which is the NOR operation.

Post a Comment for "How To Make A Bitwise Nor Gate"