strange behavior of & and ^ in python 2.7 -


here code , wondering why different results in both cases? expect first line output -1, since bit , 0xffffffff not change anything. , expect second line output 1, since bit xor 0xffffffff means bit not (which ~ in python, , adding 1 should gets -1's two's complement value, 1)

print -1 & 0xffffffff # output 4294967295 print -1 ^ 0xffffffff + 1 # output -4294967297 

python implements integers arbitrary precision. when performing bit-wise operations, positive numbers treated if have infinite sequence of high-order 0 bits, while negative numbers act have infinite sequence of high-order 1 bits. in particular, number -1 acts infinite sequence of 1's.

so first calculation have

    ...11111111111111111111111111111111111111111111111111111111   & ...00000000000000000000000011111111111111111111111111111111   = ...00000000000000000000000011111111111111111111111111111111 

since has 0 in high-order bits, it's positive result.

the second calculation is:

    ...11111111111111111111111111111111111111111111111111111111   ^ ...00000000000000000000000100000000000000000000000000000000 (this 0xffffffff + 1 = 0x100000000)   = ...11111111111111111111111011111111111111111111111111111111 

since has 1 in high-order bits, it's negative result.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -