[Tutor] XOR, bytes and strings

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 4 23:54:20 CET 2006



On Wed, 4 Jan 2006, to bifu wrote:

> thanks for the help, but my problem is how to use that for a string,

Hi To,

A character can be translated into an ordinal number by using the ord()
function.  For example:

######
>>> ord('a')
97
######


> and those hexadecimals are confusing me, too.

Let's talk about this a bit.  Do you understand that hexadecimal is a
compact way of writing out numbers or bit patterns?

For example:

######
>>> 0xff
255
######

shows us that the bit pattern consisting of eight 1's:

    1 1 1 1   1 1 1 1

can be seen as the number 255.  (2**7 + 2**6 + ... + 2**1 + 2**0).  The
reason that 0xff corresponds to that particular bit pattern of all-ones is
because of this relationship between bits and hex digits:

 bits   hex
 ----   ---
 0000    0
 0001    1
 0010    2
 0011    3
 0100    4
 0101    5
 0110    6
 0111    7
 1000    8
 1001    9
 1010    A
 1011    B
 1100    C
 1101    D
 1110    E
 1111    F



> if it are only bits, it's easy to understand, but how to use XOR for bytes?

XOR works for bytes too.  Let's define a byte to be a number between 0 and
255, inclusive.  Let's play with the pattern:

   10101010   (0xaa)

and xor it against:

   01010101   (0x55)

We know what to expect: 11111111  (0xff), but let's try it:

######
>>> 0xaa ^ 0x55
255
######

We know that 255 corresponds to the bit pattern 11111111, so things appear
to be working.


If this is the first time you've seen stuff like this, this might seem
really weird.  Please feel free to ask more questions about this.


By the way, another thread this week is doing similar stuff with bitwise
arithmetic; you may want to look at it:

    http://mail.python.org/pipermail/tutor/2006-January/044244.html


Good luck!



More information about the Tutor mailing list