I have the following C function:
unsigned int DJBHash(char* str, unsigned int len)
{
unsigned int hash = 5381;
unsigned int i = 0;
for(i = 0; i < len; str++, i++)
{
hash = ((hash << 5) + hash) + (*str);
}
return hash;
}
I’m trying to convert it to Javascript. I’m having trouble with the (*str) part of line 8
(`hash=((hash << 5) + hash) + (*str)`).
How can I efficiently convert my javascript string into the same representation as is done in C?
Here’s what I’ve done sofar, but it’s not working: when I add zero to “str”, it simply appends a character “0” to my str. What am I doing wrong?
function DJBHash(str,len){
var hash=5381;
var i=0;
for(i=0;i<len;i++){
hash=((hash<<5)+hash)+(str+0);
}
return hash;
}
There are no pointers in Javascript. Treat the input as a string instead of a pointer to a string. The string has a length, so you don’t need to send that as a parameter, and the string object has the
charCodeAtmethod that you can use to get the character code of a specific character during the loop:However, the C code might rely on the
intto have a specific size (which is however not according to the C specifications), to use the overflow to limit the result to a specific number of bits. As Javascript doesn’t have any integer type, you would have to use integer operations to limit the result in the same way. This would produce a 32 bit result: