Good way to generate an int from a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mrhoopz
Forum Newbie
Posts: 11
Joined: Tue Feb 06, 2007 1:35 pm

Good way to generate an int from a string

Post by mrhoopz »

I have some code that runs a program and generates an output image that is dependent on a number of parameters. I am currently attaching a random number to the filename of each image, but what I would like to do is combine all the parameters into one long string and use that string to generate a the number. That way, if a user chooses parameters that they've already used, I can use file_exists to check and see if the image has already been produced.

Right now I am using the function crc32, but the fact that the generated number is sometimes negative just sorta bugs me. I could take the absolute value, but then I run the risk (albeit miniscule) of having crc(string1) = x and crc(string2) = -x, which would incorrectly imply that string1=string2.

Besides, I'm sure there is a better and faster way to do this than using crc32.

Thanks!
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I've used sha1() to gererate filenames before - but usually based on the file contents. You could still take the sha1 of all the parameters, and the chances of a collision are extremely small.

You could also use md5(), but don't use both at the same time (double hashing) as it will lessen the cardinality of your result while taking longer.
mrhoopz
Forum Newbie
Posts: 11
Joined: Tue Feb 06, 2007 1:35 pm

Post by mrhoopz »

Thanks Kieran, I looked at sha1() and md5(), but I just didn't really want that many characters at the end of the filename. I have no good reason, why, I just liked the fact that crc32() only gave you about 10. I guess when it comes down to it, I'm not really worried about a collision occuring, so I might as well just use abs(crc32(my_str)) to get a non-negative 9 or 10 digit number.

I guess my main question was, is there a better and/or faster way of doing this than using one of those three functions, but it sounds like those are probably it.
Post Reply