[Tutor] Strange operator

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Nov 5 03:47:50 CET 2004



On Thu, 4 Nov 2004, Chad Crabtree wrote:

> So if I understand this correctly it's similar to the chmod 777
> directive, using binary representation to mean (111)  I understood
> this
> system already but that is really neat.  So to extrapolate
>
> LEFT=1
> RIGHT=2
> TOP=4
> BOTTOM=8
> WILLYWONKA=16
>
> would be the proper progression of options.


Hi Chad,


Yup, exactly.  Each of those numbers corresponds to a bit pattern where
one of those bits is set on.


> if flag>=WILLYWONKA:
>     print "Go to the Factory"


Yes.  In the general case, we'd use an AND operator to see if a flag were
set:

    if flags & LEFT:
        print "Turning left!"



> So this is like a really really really compact switch statement?

It's a very compact way of storing lots of individual flags.


These bitwise operators aren't just for representing flags, though,
because of the fact that the bitwise operators work against all the bits
in an integer at once.  It might be good to mention another common
application for these bitwise operators.


One fairly well-known bitwise operator is called XOR, the thing that
toggles bits on or off.  Characters can be represented as integers, so we
can jury-rig a really silly program to obscure text just with XOR:

###
>>> msg = map(ord, "hello world")
>>> msg
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
###


So there's our message as a list of numbers.  We can now apply an XOR
across each number:

###
>>> def encode(numbers, magicKey=42):
...     return [n ^ magicKey for n in numbers]
...
>>> encode(msg)
[66, 79, 70, 70, 69, 10, 93, 69, 88, 70, 78]
###



And just as toggling something twice gets us back to where we started,
XORing twice --- with the same pattern --- handles the decryption:

###
>>> encode(encode(msg))
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
###

Of course, this is an abysmal way to do encryption.  *grin* But these
operators (including XOR) are actually at the heart of some encryption
programs.




I hope this helps!



More information about the Tutor mailing list