Skip to content

Instantly share code, notes, and snippets.

@myfonj
Last active February 27, 2024 11:29
Show Gist options
  • Save myfonj/2e86d790e5fe7f662cd4cb5fb079d88a to your computer and use it in GitHub Desktop.
Save myfonj/2e86d790e5fe7f662cd4cb5fb079d88a to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/questions/40958727/javascript-generate-unique-number-based-on-string
(() => {
function base0xFFFFtoBigInt(str) {
const base = BigInt(0xFFFF);
let result = BigInt(0);
let pow = 0;
let i = str.length;
while (i-->0) {
const charCode = BigInt(str.charCodeAt(i));
result += charCode * (base ** BigInt(pow++));
}
return result
}
function bigIntToBase0xFFFF(int) {
int = BigInt(int);
const base = BigInt(0xFFFF);
let result = '';
while (int) {
let rest = int % base;
result = String.fromCharCode(Number(rest)) + result;
int -= rest;
int /= base;
}
return result;
}
const input = '_';
const nr = base0xFFFFtoBigInt(input);
console.log('input: %s; output: %s', input, nr)
const str = bigIntToBase0xFFFF(nr);
console.log(str,'!!!');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment