python蟒蛇程序注释_如何做一个按位或非门在Python(编辑蟒蛇数学为我工作)

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 I deal with the resembling values:

Python would want to do this:

a + b = 2200011

but what I want it to do is this

if 0 and 0 are attempted to be added together show 1

if 1 and 0 are attempted to be added together show 0

if 0 and 1 are attempted to be added together show 0

if 1 and 1 are attempted to be added together show 0

What I wish to do is a + b = 10011100

Is there a way to edit the way python works out maths in this instance?

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

so could anyone give example of a code to give set values (1+1=0)(0+0=1) ... e.g

解决方案

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: http://stackoverflow.com/a/19203069/1787973

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值