goul
goul

Reputation: 853

Generate a unique integer based on given string

There are many answers already on the subject, but I can't find any that looks like what I'm looking for.

I would need to generate a unique negative ID (int) from a given string. Would be happy if there was the decoding as well, but not mandatory.

Upvotes: 0

Views: 6511

Answers (3)

Nikita B
Nikita B

Reputation: 3333

Obviously, there is no such conversion. int size is limited by 32 bits, while string size is pretty much unlimited. You will get collisions unless you apply some restrictions to your strings.

Upvotes: 4

AK_
AK_

Reputation: 8099

It is impossible to generate a unique int for an arbitrary length string.

int has 32 bits of data, a string of 100 characters (assuming C#) will have 1600 bits of data, so you will have at least 1600/32 collisions.

[being funny]

you could :

string a = "dgfadg";
var bytes = System.Text.Encoding.Unicode.GetBytes(a);
BigInteger integer=  new BigInteger(bytes);

[/being funny]

Upvotes: 0

Bas
Bas

Reputation: 27105

You could try myString.GetHashCode() it's not guaranteed to be unique, but will definetely return the same key for the same string.

Upvotes: 4

Related Questions