4

I am working on an encryption puzzle and am needing to take the exclusive or of two binary numbers (I'm using the operator package in Python). If I run operator.xor(1001111, 1100001) for instance I get the very weird output 2068086. Why doesn't it return 0101110 or at least 101110?

dsaxton
  • 995
  • 2
  • 10
  • 23

3 Answers3

10

Because Python doesn't see that as binary numbers. Instead use:

operator.xor(0b1001111, 0b1100001)
ale
  • 6,369
  • 7
  • 55
  • 65
Ewoud
  • 741
  • 4
  • 6
7

The calculated answer is using the decimal values you provided, not their binary appearance. What you are really asking is...

1001111 ^ 1100001

When you mean is 79 ^ 97. Instead try using the binary literals as so...

0b1001111 ^ 0b1100001

See How do you express binary literals in Python? for more information.

Community
  • 1
  • 1
Hunter Larco
  • 785
  • 5
  • 17
0

Because 1001111 and 1100001 are not binary numbers. 1001111 is One million, one thousand, one hundred and eleven, while 1100001 is One million, one hundred thousands and one. Python doesn't recognize these as binary numbers. Binary numbers have to be prefixed with 0b to be recognized as binary numbers in Python/Python 3. So the correct way is this:

operator.xor(0b1001111, 0b1100001)

But hey! We get 46 as output. We should fix that. Thankfully, there IS a built-in in Python/Python 3. It's the function bin(n). That function prints a number a binary, prefixed with 0b. So our final code would be:

bin(operator.xor(0b1001111, 0b1100001))

If we want to hide the 0b (mostly in cases where that number is printed to the screen), we should use [2:] like this:

bin(operator.xor(0b1001111, 0b1100001))[2:]

A shorter way (warning looks like a tutorial for something you *should* already know)
Well, operator.xor() is too big for an operator :)
If that is the case (99.9%), instead you should use a^b. I think you already know this but why to import a whole module just for the xor operator? If you like to type the word xor instead, import the operator module like this: from operator import a, b.... Then use like this: bin(xor(a,b)). I hope you already know that stuff but I want to make sure you enjoy coding even more :)

EKons
  • 887
  • 2
  • 20
  • 27