Anmol Dubey Anmol Dubey - 10 months ago 49
C Question

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

public class HelloWorld{

public static void main(String []args){
String Str = new String("");
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?

h22 h22
Answer Source

... 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;
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.