Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

python - 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 means that the result will be in binary form.
  • a is the processes going through the gate
  • 0b means base 2 form

Could someone explain the rest? I am confused about 11111111. & is the and gate (confused why this separates the two). And how would you change this to work for any other gate, e.g. XOR, NAND, or...?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...