Is it possible in Javascript to convert something like this: d131dd02c5e6eec4 693d9a0698aff95c 2fcab58712467eab 4004583eb8fb7f89
, which is the result of an MD5 hash function, into an integer ?
Is it possible in Javascript to convert something like this: d131dd02c5e6eec4 693d9a0698aff95c 2fcab58712467eab 4004583eb8fb7f89
, which is the result of an MD5 hash function, into an integer ?
- What do you want the integer for? You could convert it to a string, but not a JavaScript number (accurately, anyways). – Ry- ♦ Commented Jun 20, 2013 at 13:42
- I'm trying to implement the Chord protocol. – AndreiBogdan Commented Jun 20, 2013 at 13:43
- The only way you could even begin to cast it as an int is by using some form of substitution to replace the letters with a number, which creates a whole set of other issues... – Justin Commented Jun 20, 2013 at 13:44
- @AndreiBogdan: So, to implement the Chord protocol, what calculation do you need to do on the hash (as an integer)? – Ry- ♦ Commented Jun 20, 2013 at 13:46
- 2 In the article describing the protocol it says "The consistent hash function assigns each node and key an m bit identifier using SHA-1 as a base hash function. A node’s identifier is chosen by hashing the node’s IP address [...]". So I can arrange these values 'around a circle', just by comparing the strings, but later on it says that each node has a list of successors: "s = successor(n+2^i), where 0 <= i <= m-1 (and all arithmetic is modulo 2^m)." m in the case of MD5 (which I'm using) is 128. I might be wrong, but I need to be able to perform modulo on the hash function. o.O – AndreiBogdan Commented Jun 20, 2013 at 14:02
4 Answers
Reset to default 7May not be perfect, but this suited my needs
export function stringToIntHash(str, upperbound, lowerbound) {
let result = 0;
for (let i = 0; i < str.length; i++) {
result = result + str.charCodeAt(i);
}
if (!lowerbound) lowerbound = 0;
if (!upperbound) upperbound = 500;
return (result % (upperbound - lowerbound)) + lowerbound;
}
ES6 version, string to integer between 0-9:
string.split('').map(i => i.charCodeAt(0)).reduce((a, b) => a + b, 0) % 10
That looks like a hexadecimal number, so you could try using the parseInt
function and pass in a base of sixteen:
var num = parseInt(string, 16);
Edit: This method doesn't actually work. See the comments for details.
Maybe this one https://github.com/lovell/farmhash ?
const farmhash = require('farmhash');
const hexDigest = crypto.createHash('md5').update().digest('hex');
farmhash.fingerprint64(hexDigest);