简体   繁体   English

按位运算符:仅使用 & 和 ~ 来获得 ^

[英]Bitwise Operators: Using only & and ~ to get ^

I've been stuck on a bonus my professor gave for a couple of days now:我被教授给的奖金困住了几天:

  • give x^y using only ~ and &仅使用 ~ 和 & 给出 x^y
  • Assume the machine use twos complement, 32-bit representations of integers.假设机器使用二进制补码,整数的 32 位表示。

I've tried many different combinations, and also tried to write out the logic of the operator ^, but it hasn't been working out.我尝试了很多不同的组合,也尝试写出运算符^的逻辑,但一直没有解决。 Any hints or help would be much appreciated!任何提示或帮助将不胜感激!

the XOR operator can in fact be written as a combnation of those two, I'll put this in two steps: XOR 运算符实际上可以写为这两者的组合,我将把它分为两步:

A NAND B = NOT(A AND B) A 与非 B = 非(A 与 B)

A XOR B = (A NAND (A NAND B)) NAND (B NAND (A NAND B)) A XOR B = (A NAND (A NAND B)) NAND (B NAND (A NAND B))

Like described before on math:就像之前在数学上描述的那样:

https://math.stackexchange.com/questions/38473/is-xor-a-combination-of-and-and-not-operators https://math.stackexchange.com/questions/38473/is-xor-a-combination-of-and-and-not-operators

First, suppose you had each of the & , |首先,假设你有每个& , | , and ~ operators available to you. , 和~运算符可供您使用。 Could you implement ^ that way?你能这样实现^吗?

Next, see if you can find a way to express |接下来看看能不能找到表达方式| purely in terms of & and ~ .纯粹就&~

Finally, combine those ideas together.最后,将这些想法结合在一起。

Good luck!祝你好运!

You could try to draw the truth tables for XOR , AND , and, OR您可以尝试为XORAND 、 and 、 OR绘制真值表

a b  a^b
0 0   0
0 1   1
1 0   1
1 1   0

a b  a|b
0 0   0
0 1   1
1 0   1
1 1   1

a b  a&b
0 0   0
0 1   0
1 0   0
1 1   1

next find how to use |接下来找到如何使用| and & to build this&来构建这个

a|b give all the three first rows correct, a&b give the other line. a|b给出所有前三行正确, a&b给出另一行。 If we negate it it can be used to mask the wanted lines!如果我们否定它,它可以用来掩盖想要的线条! So we could phrase xor as:所以我们可以将 xor 表述为:

(a or b) but not when (a and b) (ab)不是当 (ab)

There is no but in boolean algebra so it becomes an and which leads to this:在布尔代数中没有but所以它变成了and导致了这个:

(a|b)&~(a&b)

Edit: Pointed out I was answering the wrong question, use The law of DeMorgan to build the or编辑:指出我回答了错误的问题,使用德摩根定律来构建或

~(~a & ~b)

gives the answer to be给出的答案是

~(~a&~b)&~(a&b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM