Javascript: Please help me convert this C function to Javascript
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 havin开发者_如何学Pythong 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 charCodeAt
method that you can use to get the character code of a specific character during the loop:
function DJBHash(str) {
var hash = 5381;
for(var i = 0; i < str.length; i++) {
hash = ((hash << 5) + hash) + str.charCodeAt(i);
}
return hash;
}
However, the C code might rely on the int
to 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:
function DJBHash(str) {
var hash = 5381;
for(var i = 0; i < str.length; i++) {
hash = (((hash << 5) + hash) + str.charCodeAt(i)) & 0xffffffff;
}
return hash;
}
I think you mean str.charCodeAt(i)
, not str+0
.
Just get rid of the pointer shenanigans, and iterate using only i
:
for(i = 0; i < len; i++)
{
hash = ((hash << 5) + hash) + (str.charAt(i));
}
精彩评论