12

How to create simple hash value? For example I have string "TechnologyIsCool" and how to have hash value from this string?

I want to do some method like:

public string HashThis(string value)
{
    string hashResult = string.Empty;

    ...

    return hashResult;
}

and call this method like:

string hash = HashThis("TechnologyIsCool");

and after that have hash like "5qazws".

Smit
  • 609
  • 3
  • 11
  • 27
  • 4
    Why you don't want to use String.GetHashCode()? – Blablablaster May 16 '12 at 10:24
  • 4
    What kind of hash? An indexing hash? A cryptographic hash? – Polynomial May 16 '12 at 10:26
  • I want to understand how work the short links. Is it should be custom hash? – Smit May 16 '12 at 10:35
  • 1
    My guess is that the folks doing shortened links are storing the original link in a database and then [Base64](http://msdn.microsoft.com/en-us/library/system.convert.tobase64string.aspx) encoding the identification assigned to the row. A hash does not produce a unique value and collisions wouldn't make TinyURL too popular, e.g. a link that gets you either kittens or the national budget. – HABO May 16 '12 at 11:21

3 Answers3

13

Use String.GetHashCode Method

 public static void Main() 
    {
        DisplayHashCode( "Abcdei" );
    }

static void DisplayHashCode( String Operand )
{
    int     HashCode = Operand.GetHashCode( );
    Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}",
                      Operand, HashCode );
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 7
    The hashcode can vary on different runtimes. Some warnings that apply to this solution can be found here: http://stackoverflow.com/questions/1116860/whats-the-best-way-to-create-a-short-hash-similiar-to-what-tiny-url-does – Magge Sep 13 '13 at 07:53
6

Use GetHashCode();

public string HashThis(string value)
{
    return hashResult = value.GetHashCode();
}
dtsg
  • 4,408
  • 4
  • 30
  • 40
  • 8
    The hashcode can vary on different runtimes. Some warnings that apply to this solution can be found here: http://stackoverflow.com/questions/1116860/whats-the-best-way-to-create-a-short-hash-similiar-to-what-tiny-url-does – Magge Sep 13 '13 at 07:54
2

No you cannot use String.GetHashCode() because this does not guarantee to return the same hash on the same string every time.