How do binary operations with XOR work in python?

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

print (10000000 ^ 10100111) 

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

print (100 ^ 101) 

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

print int(a) ^ int(b) 

I am still getting the result 166671.

Questions:

  • Why am I getting result 166671 instead of binary result 00100111?

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

I am running Python version 2.7.2.

+4
source share
2 answers

100 100 (1100100 ). 0bnnn .

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

>>> 0b100 ^ 0b101
1

>>> 0b100 & 0b101
4
>>> bin(0b100 & 0b101)
'0b100'
>>> '{:b}'.format(0b100 & 0b101)
'100'
+3

, .

10000000^10100111

0b100110001001011010000000 ^ 0b100110100001110110001111

0b101000101100001111

,

166671 

100 ^ 101

0b1100100 ^ 0b1100101

0b1

, ( , ),

1
+2

All Articles