4

I have the following problem with the xor operator (^) in python. I have two binary numbers, let a = 10100111 and b = 10000000. When I use the xor operator,

print (10000000 ^ 10100111) 

I get the result of 166671 instead of 00100111. However, when I use

print (100 ^ 101) 

I get the appropriate result in binary of 1 (001). Even if I use

print int(a) ^ int(b) 

I still get the result of 166671.

Questions:

  1. Why do I get the result of 166671 instead of the binary result of 00100111?

  2. Why do I get the appropriate result when I use 100^101?

I am running Python version 2.7.2.

1
  • Aside: this isn't related to your issue here, but one thing that often surprises people in Python 2 is that 010 isn't either 10 (read in decimal) or 2 (read in binary), it's 8. The 0 prefix, without a b, means "read this number as octal, i.e. base 8". Just a heads-up. Commented Oct 8, 2013 at 16:47

2 Answers 2

3

100 is decimal 100 (1100100 in binary). Use 0bnnn form for binary representation.

>>> 0b100
4
>>> 100
100
>>> 0b100 == 100
False

>>> 0b100 ^ 0b101
1

>>> 0b100 & 0b101
4
>>> bin(0b100 & 0b101)
'0b100'
>>> '{:b}'.format(0b100 & 0b101)
'100'
Sign up to request clarification or add additional context in comments.

2 Comments

please tell solution for python 3.x , say x=100 and y=101 x^y
@AkhilNadhPC, bin(0b100 ^ 0b101) works in Python 3.
2

You are using decimal number representations, not binary.

10000000^10100111

in binary is

0b100110001001011010000000 ^ 0b100110100001110110001111

which equals

0b101000101100001111

or in decimal,

166671 

100 ^ 101

in binary is

0b1100100 ^ 0b1100101

which is

0b1

or, in decimal (which happens to be the same as in binary in this case),

1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.