Re: python hash() function

Discussion in 'Python' started by Terry Reedy, Mar 26, 2008.

  1. Terry Reedy

    Terry Reedy Guest

    "Alvin Delagon" <> wrote in message
    news:...
    | Hello,
    |
    | >>> hash("foobar")
    | -1969371895
    |
    | Anyone can explain to me how the hash() function in python does its work?
    A
    | link to its source could help me a lot also. I'm looking for a way to
    | replicate this function in php. Thanks in advance.

    If not part of your installation, start with svn.python.org and click
    browse. I would look for builtins.c or somesuch.
    Terry Reedy, Mar 26, 2008
    #1
    1. Advertising

  2. Terry Reedy

    Dan Bishop Guest

    On Mar 25, 9:22 pm, "Terry Reedy" <> wrote:
    > "Alvin Delagon" <> wrote in message
    >
    > news:...
    > | Hello,
    > |
    > | >>> hash("foobar")
    > | -1969371895
    > |
    > | Anyone can explain to me how the hash() function in python does its work?
    > A
    > | link to its source could help me a lot also. I'm looking for a way to
    > | replicate this function in php. Thanks in advance.
    >
    > If not part of your installation, start with svn.python.org and click
    > browse. I would look for builtins.c or somesuch.


    It's in stringobject.c:

    static long
    string_hash(PyStringObject *a)
    {
    register Py_ssize_t len;
    register unsigned char *p;
    register long x;

    if (a->ob_shash != -1)
    return a->ob_shash;
    len = Py_Size(a);
    p = (unsigned char *) a->ob_sval;
    x = *p << 7;
    while (--len >= 0)
    x = (1000003*x) ^ *p++;
    x ^= Py_Size(a);
    if (x == -1)
    x = -2;
    a->ob_shash = x;
    return x;
    }
    Dan Bishop, Mar 26, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Red Orchid
    Replies:
    3
    Views:
    1,025
  2. Pieter Claassen
    Replies:
    1
    Views:
    1,093
    CBFalconer
    Aug 4, 2004
  3. Bo Peng
    Replies:
    4
    Views:
    780
  4. rp
    Replies:
    1
    Views:
    494
    red floyd
    Nov 10, 2011
  5. Srijayanth Sridhar
    Replies:
    19
    Views:
    596
    David A. Black
    Jul 2, 2008
Loading...

Share This Page