26

I'm trying to xor 2 binaries using python like this but my output is not in binary any help?

a = "11011111101100110110011001011101000"
b = "11001011101100111000011100001100001"
y = int(a) ^ int(b)
print y
karthikr
  • 97,368
  • 26
  • 197
  • 188

4 Answers4

37
a="11011111101100110110011001011101000"
b="11001011101100111000011100001100001"
y=int(a,2) ^ int(b,2)
print('{0:b}'.format(y))
coder
  • 37
  • 7
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • It don't give me the answer with the same length –  Oct 16 '13 at 22:06
  • If you want the answer to print with the same length, try: `print '{0:0{1}b}'.format(y,len(a))` – Robᵩ Oct 16 '13 at 22:12
  • now it's working what was the last thing because xor table should be like this a = 1 and b = 1 output= 0 a = 0 and b = 0 output= 0 a = 0 and b = 1 output= 1 a = 1 and b = 0 output= 1 –  Oct 16 '13 at 22:17
  • 4
    please think about update it with a python 3 version compatible, since python 2.x is mostly not supported anymore. – VP. Apr 09 '20 at 07:54
10

To get the Xor'd binary to the same length, as per the OP's request, do the following:

a = "11011111101100110110011001011101000"
b = "11001011101100111000011100001100001"
y = int(a, 2)^int(b,2)
print bin(y)[2:].zfill(len(a))

[output: 00010100000000001110000101010001001]

Convert the binary strings to an integer base 2, then XOR, then bin() and then skip the first two characters, 0b, hence the bin(y0)[2:].
After that, just zfill to the length - len(a), for this case.

Cheers

Matan Itzhak
  • 2,702
  • 3
  • 16
  • 35
BigH
  • 340
  • 4
  • 6
0

Since you are trying to carryout XOR on the same length binaries, the following should work just fine:

c=[str(int(a[i])^int(b[i])) for i in range(len(a))]
c=''.join(c)

You can avoid the formatting altogether.

Amiay Narayan
  • 461
  • 9
  • 8
-2

Since you are starting with strings and want a string result, you may find this interesting but it only works if they are the same length.

y = ''.join('0' if i == j else '1' for i, j in zip(a,b))

If they might be different lengths you can do:

y = ''.join('0' if i == j else '1' for i, j in zip(a[::-1],b[::-1])[::-1])
y = a[len(y):] + b[len(y):] + y
dansalmo
  • 11,506
  • 5
  • 58
  • 53