#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    35
    Rep Power
    11

    Question XORing string elements?


    Hello all,

    I'm new to Python and I have a problem that I just can't seem to solve...

    Using the sha module I have made a 20-byte string that contains the SHA-1 hash of a file. Now I need to reduce that string a 5-byte string that is a function of the SHA-1 hash. To put it in C++ terms, I'd like to do something like:

    unsigned char new_hash[5];
    new_hash[0] = sha_hash[0] ^ sha_hash[5] ^ sha_hash[10] ^ sha_hash[15];
    new_hash[1] = sha_hash[1] ^ sha_hash[6] ^ sha_hash[11] ^ sha_hash[16];
    new_hash[2] = sha_hash[2] ^ sha_hash[7] ^ sha_hash[12] ^ sha_hash[17];
    new_hash[3] = sha_hash[3] ^ sha_hash[8] ^ sha_hash[13] ^ sha_hash[18];
    new_hash[4] = sha_hash[4] ^ sha_hash[9] ^ sha_hash[14] ^ sha_hash[19];

    But XORing only works on ints and longs, and converting any string doesn't rely on its underlying bit pattern (understandably so... e.g., '1' converts to the integer 1, not its underlying bit value 31).

    Is this trivial? Any help or ideas would be much appreciated!

    Thanks,
    - the perfect soup
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    11
    The trivial reply would be to suggest the use of the builtin 'ord' function. "ord('1')" returns 49, while "hex(ord('1'))" returns 0x31. The other two such convertion functions are 'chr' and the 'oct'.
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Another useful conversion function, 'str', which convers objects of another type to a string. You could also do this with..

    Code:
    'this is a string %s' % (other_type)
    Have fun,
    Mark.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    35
    Rep Power
    11
    Yay, the ord() trick works... Using chr() I can complte building the new string:

    val0 = ord(sha_hash[0]) ^ ord(sha_hash[5]) ^ ord(sha_hash[10]) ^ ord(sha_hash[15])
    val1 = ord(sha_hash[1]) ^ ord(sha_hash[6]) ^ ord(sha_hash[11]) ^ ord(sha_hash[16])
    val2 = ord(sha_hash[2]) ^ ord(sha_hash[7]) ^ ord(sha_hash[12]) ^ ord(sha_hash[17])
    val3 = ord(sha_hash[3]) ^ ord(sha_hash[8]) ^ ord(sha_hash[13]) ^ ord(sha_hash[18])
    val4 = ord(sha_hash[4]) ^ ord(sha_hash[9]) ^ ord(sha_hash[14]) ^ ord(sha_hash[19])
    new_hash = chr(val0) + chr(val1) + chr(val2) + chr(val3) + chr(val4)

    Everything should now go smoothly... Thanks for your help guys!

    - the perfect soup

IMN logo majestic logo threadwatch logo seochat tools logo