[Tutor] What is the augmented assignment operator "^="
Alan Gauld
alan.gauld at btinternet.com
Mon Feb 19 13:54:13 CET 2007
"Dick Moores" <rdm at rcblue.com> wrote
> Thanks, Andre! I've got it for the three operators, for non-negative
> integers. But I'm not sure I understand how negative integers work.
> For example, is 3 & -3 = 1
> because it is 11 & -11 = 01, and that's because one of the first
> digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1,
> Q.E.D.?
Remember that the digits are 32 bits long so 3 is not 11
but
00000000000000000000000000000000011
And the representation of negative numbers is more complex
than you might think.
You can see the full hex representations using struct:
>>> import struct
>>> struct.pack('i',-3)
'\xfd\xff\xff\xff'
>>> struct.pack('i',3)
'\x03\x00\x00\x00'
Since most of 3 is zeros the and results will be zro, so
lets look at the significant bits:
>>> 0xfd & 0x03
1
>>>
voila!
> Also, of what practical use are these things?
Take a look at my Using the OS topic, there is a side-bar(box)
just short of half way down that describes how these can be
used to test file status. There are many other uses too, but
that's one real-world case.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list