0

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.

1
  • 6
    Unique in what context? Universally, per network, per computer, per session, per user, per process, or what? Commented Apr 15, 2013 at 10:10

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

And if it isn't already negative, he'd need to negate it. That's going to double the number of collisions of course.
"The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across versions of the .NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the .NET Framework. In some cases, they can even differ by application domain." msdn.microsoft.com/en-us/library/…
4

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.

1 Comment

Good remark. I am using the answer proposed below but will pay attention to my string length. thanks
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.