Reputation: 15
I have a function djb2
on php and javascript,
php
function hash_djb2($str){
$hash = 5381;
$length = strlen($str);
for($i = 0; $i < $length; $i++) {
$hash = (($hash << 5) + $hash) + $str[$i];
}
return $hash;
}
and javascript
djb2Code = function(str){
var hash = 5381;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
}
return hash;
}
on php I call
hash_djb2("123456789egrdhfdtjdtjdtjrt");
and the output is
-4235984878
and in javascript I call
djb2Code("123456789egrdhfdtjdtjdtjrt");
and the output is
27338942
Why is that and how can I fix it?
Thank you
Upvotes: 0
Views: 73
Reputation: 4370
you have to use ord in php code
hash = (($hash << 5) + $hash) + ord($str[$i]);
Upvotes: 0
Reputation: 2119
Those are not the same functions. Your PHP uses $str[$i]
, which is a character. Your JavaScript function uses char.charCodeAt(i)
which returns integer.
Change your PHP function like this ...
function hash_djb2($str){
$hash = 5381;
$length = strlen($str);
for($i = 0; $i < $length; $i++) {
$char = ord($str[$i]); // this line is added
$hash = (($hash << 5) + $hash) + $char; // this line is modified
}
return $hash;
}
Upvotes: 1