简体   繁体   中英

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 &
  • Assume the machine use twos complement, 32-bit representations of integers.

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:

A NAND B = NOT(A AND 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

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

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. If we negate it it can be used to mask the wanted lines! So we could phrase xor as:

(a or b) but not when (a and b)

There is no but in boolean algebra so it becomes an and which leads to this:

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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