I'm not able to get the same djbhash in javascript that I was getting in swift.
extension String {
public func djbHash() -> Int {
return self.utf8
.map {return $0}
.reduce(5381) {
let h = ($0 << 5) & $0 & Int($1)
print("h", h)
return h
}
}
}
var djbHash = function (string) {
var h = 5381; // our hash
var i = 0; // our iterator
for (i = 0; i < string.length; i ) {
var ascii = string.charCodeAt(i); // grab ASCII integer
h = (h << 5) h ascii; // bitwise operations
}
return h;
}
I tried using BigInt but the value for QHChLUHDMNh5UTBUcgtLmlPziN42 im getting is 17760568308754997342052348842020823769412069976n compared to 357350748206983768 in swift
CodePudding user response:
The Swift &
operator is an “overflow operator”: It truncates the result of the addition to the available number of bits for the used integer type.
A Swift Int
is a 64-bit (signed) integer on all 64-bit platforms, and adding two integers would crash with a runtime exception if the result does not fit into an Int
:
let a: Int = 0x7ffffffffffffff0
let b: Int = 0x7ffffffffffffff0
print(a b) //