Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
July 29th, 2003, 04:30 PM
 theperfectsoup
Contributing User

Join Date: Jul 2003
Posts: 35
Time spent in forums: < 1 sec
Reputation Power: 11
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
July 29th, 2003, 05:41 PM
 percivall
Contributing User

Join Date: Jul 2003
Posts: 133
Time spent in forums: < 1 sec
Reputation 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'.

#3
July 29th, 2003, 06:09 PM
 netytan
Hello World :)

Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
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.

#4
July 29th, 2003, 07:26 PM
 theperfectsoup
Contributing User

Join Date: Jul 2003
Posts: 35
Time spent in forums: < 1 sec
Reputation 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

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > XORing string elements?