如何做一个按位或非门在Python(编辑蟒蛇数学为我工作) [英] How to do a bitwise NOR Gate in Python (editing python maths to work for me)
问题描述
说,我写这篇文章:
a=01100001
b=01100010
c=01100011
d=01100100
e=01100101
每个字母现在类似于给定数字我会怎么对付外形酷似值:
each letter resembles the given numbers now how would I deal with the resembling values:
Python的想做到这一点:
Python would want to do this:
a + b = 2200011
但我希望它做的是
but what I want it to do is this
- 如果0和0试图加在一起显示1
- 如果1和0试图被加在一起显示0
- 如果0和1试图加在一起显示0
- 如果1和1试图加在一起显示0
我希望做的是 A + B = 10011100
是否存在编辑蟒蛇方式的工作方式了数学在这种情况?
Is there a way to edit the way python works out maths in this instance?
就目前为止我已经给定值重新present字母,但我想要做的就是改变方式,蟒蛇给我结果的解释匹配异或门上方
do far i have given set values to represent the letters but i want to do is change the way that python gives me results to match XOR gate in the explanation above
所以任何人都可以给例如code的给定值(1 + 1 = 0)(0 + 0 = 1)...例如
so could anyone give example of a code to give set values (1+1=0)(0+0=1) ... e.g
推荐答案
您说:
我希望做的是A + B = 10011100
What I wish to do is a + b = 10011100
我的解决方案:
>>> a=0b01100001
>>> b=0b01100010
>>> bin((a | b) ^ 0b11111111)
'0b10011100'
现在,您的解释:
您所要求的一个NOR位运算( http://en.wikipedia.org/wiki/NOR_gate 如果它不是很明显):
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)
在Python的:
>>> bin((a ^ 0b11111111) & (b ^ 0b11111111))
'0b10011100'
您也可能不知道那是什么 ^ 0b11111111
。好吧,不是
等同于 A XOR 1
和 XOR
写入 ^
在Python。我建议你写下的逻辑表,如果你不相信100%。所以基本上, ^ 0b11111111
更改0到1和1比0。
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.
的斌
函数提供给作为参数的数字的二进制重新presentation。在 0B
在号码开始意味着该数字在基地2(否则它的基数为10)。
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).
编辑:
起初,我对这个问题首先想到的是:
Initially, my first thought for this problem was:
bin(~(a|b))
但结果是' - 0b1100100
。这是因为,在Python数量被签署。但它也有可能通过仅保持第一字节,以获得良好的结果:
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'
编辑2:
我刚刚发现,OP问另外一个问题,以更好地理解我的答案。所以,如果你想知道为什么我用了XOR做不,在这里看到了很好的解释:<一href=\"http://stackoverflow.com/a/19203069/1787973\">http://stackoverflow.com/a/19203069/1787973
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: http://stackoverflow.com/a/19203069/1787973
这篇关于如何做一个按位或非门在Python(编辑蟒蛇数学为我工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!