Thursday, July 1, 2010

Converting string to unique integer in perl

I'm writing some perl code for a project I'm working on. One of my needs is to convert a string into a 32-bit integer. The catch is that the conversion must be deterministic (i.e. a hash function).

I looked at using CRC32 but the resulting integer wasn't always the same each time. I looked at using MD5, but MD5 produces a very long hex string that will overflow a 32-bit integer.

I decided to do something a bit weird; because a 32 bit integer has up to 4,294,967,295 values (signed), I could take the first 8 characters in the MD5 value and then convert any of the letters to a corresponding number.

So the function looks like this in perl:

sub convert_string
# Function to convert string into a unique 32-bit integer
{
 my ($str) = @_;
 
 my $md5str = md5_hex($str);
 my $md5strsub = substr $md5str, 0, 8;
 $md5strsub =~ tr/a-f/1-6/;
 return $md5strsub;
}

3 Comments:

Blogger Anbarasan14 said...

Great info. Thanks for spending your valuable time to share this post.
Spoken English Classes in Chennai
Best Spoken English Classes in Chennai
IELTS Coaching in Chennai
IELTS Coaching Centre in Chennai
English Speaking Classes in Mumbai
English Speaking Course in Mumbai
IELTS Classes in Mumbai
IELTS Coaching in Mumbai
IELTS Coaching in Anna Nagar
Spoken English Class in Anna Nagar

August 8, 2019 at 2:37 AM  
Blogger invincible01 said...

Amazing Article, Really useful information to all So, I hope you will share more information to be check and share here.


inplant training
inplant training chennai
inplant training in chennai
inplant training at chennai
inplant training
inplant training chennai
inplant training in chennai
inplant training at chennai
inplant training
Inplant Training for cse

October 3, 2020 at 3:53 AM  
Blogger bamgosoocom said...

This was something I was looking for, really helpful, and great work is done. Thank you so much for
sharing such valuable information about Blog Commenting sites. This could not have been more helpful 강남오피


July 1, 2021 at 5:21 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home