Anmol Dubey
Anmol Dubey

Reputation: 125

How to replicate java hashcode in C language

I need to implement the exact same logic of java hashcode in C. A sample program in java is below

import java.io.*;
public class HelloWorld{

     public static void main(String []args){
              String Str = new String("speforums.com");
      System.out.println("Hashcode for Str :" + Str.hashCode() );
     }
}

The hashcode for above java example is 262685869. I need the same result in C language.

Using google I landed up here which implements the same in objective C - How to obtain the same result of Java String.hashCode() in Objective-C?

Upvotes: 1

Views: 3135

Answers (2)

Schwern
Schwern

Reputation: 165456

The specific behavior of Object.hashCode is not defined, but String.hashCode is.

The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

Though the code for it is rather different.

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

That can be directly translated into C.

int java_hashCode(const char *str) {
    int hash = 0;

    for (int i = 0; i < strlen(str); i++) {
        hash = 31 * hash + str[i];
    }

    return hash;
}

Upvotes: 2

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21778

... and may the source be with you, Luke

                int h = 0; // added for clarity

1496            int off = offset;
1497            char val[] = value;
1498            int len = count;
1499
1500            for (int i = 0; i < len; i++) {
1501                h = 31*h + val[off++];
1502            }
1503            hash = h;

The offset and count are offset and length of the string content in the char buffer. It need not start at 0, neither span till the end of it.

The source code is from OpenJDK here but it is supposed to return identical values. It is Java, not C, but if you know C you should be able to understand and convert.

This is for String. The default hash code of an object is derived from the object address in Java Virtual Machine. There is no way (and most likely no any sense) to replicate this.

Upvotes: 6

Related Questions