0

So I got a integer variable between 1 and 10,000.

I'd like to convert every number to a unique! hash value that has a fixed length and has a custom charset (includes all alphabetic lowercase and uppercase characters).

So:

  • n=10 could get to result="AVduujANNiO"

  • n=4507 could get to result="BciidEPpaEo"


I do not really know how to develop an algorithm like this so this is all I got so far. I think the algorithm should work but of course I get a integer value as hash - not a alphabetic value. No idea how to fix this and how to pad the result to give it a fixed length.

I really hope somebody is able to help me.

let value = "3325";


var getHash = function(value) {
  let hash = 0;
  for (let i = 0; i < value.length; i++) {
    let char = value.charCodeAt(i);
    hash = (hash << 6) + char + (char << 14);
    hash=-hash
  } return hash;
};

console.log(getHash(value))

15
  • 1
    May I ask why you want to do this? It seems pretty wasteful to use an 11 byte string to represent a 14 bit number. Commented Nov 12, 2018 at 20:04
  • 1
    Easy enough, as long as you have at least 10000 possible hash values to choose from. That depends on your fixed length and chosen charset. If your charset includes only the 62 alphanumeric chars then you need at least 3 characters. Will that do? Note that this is "base conversion", not "hashing". Commented Nov 12, 2018 at 20:04
  • 3
    Use your integer to seed a PRNG, then simply use it to fetch N "random" chars from alphabet string. Commented Nov 12, 2018 at 20:04
  • 2
    Why are you trying to make your own hash algorithm? (I hope you're not trying to roll your own crypto). Also what properties should your hash function have? Commented Nov 12, 2018 at 20:07
  • 4
    I wouldn't call this hashing at all. It sounds like you really want to convert to an arbitrary base using arbitrary characters as digits. Commented Nov 12, 2018 at 20:20

1 Answer 1

2

Here's a hash function that seems to do what you are asking for :) As a bonus, it offers no collisions til 100,000.

function h(n){
  let s = [
    '0101000', '1011010', '0011111',
    '1100001', '1100101', '1011001',
    '1110011', '1010101', '1000111',
    '0001100', '1001000'].map(x => parseInt(x, 2));
    
  let m = parseInt('101', 2);
  
  s = s.map(x => {
    n ^= m;
    m <<= 1;
    return (x ^ n) % 52;
  });

  return s.map(x =>
    String.fromCharCode(x > 25 ? 71 + x : 65 + x)
  ).join('');
}

const s = {};

for (let j=1; j <=10000; j++){
  let hash = h(j);
  
  if (s[hash])
    console.log('Collision! ' + j + ' <-> ' + s[hash]);
    
  s[hash] = j;
}

console.log('Done. No collisions below 10000.');

for (let j=1; j <11; j++)
  console.log(j, h(j));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.