3

I'm working with Youtube videos which have ids like 8DnKOc6FISU, rNsrl86inpo, 5qcmCUsw4EQ (i.e. 11 characters in the set A-Za-z0-9_-)

The goal is to convert each id to a colour (represented by the range 0-1), so they can be reliably charted.

According to this question these are 64 bit numbers. Given that:

  • I want to make full use of the colour space for any given set of videos
  • Colour perception isn't that accurate anyway

...it seems sensible to base this off the last 2-3 characters of the id.

My lead approach is a function I borrowed from here, which converts each character into a binary number like so:

    function toBin(str){
     var st,i,j,d;
     var arr = [];
     var len = str.length;
     for (i = 1; i<=len; i++){
      d = str.charCodeAt(len-i);
      for (j = 0; j < 8; j++) {
       st = d%2 == '0' ? "class='zero'" : "" 
       arr.push(d%2);
       d = Math.floor(d/2);
      }
     }
    }

But this leaves the question of how to convert this back to a float.

Any ideas for an elegant solution?

Many thanks for your help!

Community
  • 1
  • 1
Derek Hill
  • 5,965
  • 5
  • 55
  • 74

1 Answers1

3

Knowing that system is base 64 (26+26+10+2), just read each symbol, add it to total and multiply result by 64 on each iteration. In the end you will have an integer number. Divide it by maximum value to normalize it to 0-1 range.

You'll start losing precision when your IDs approach 253 though, as that's maximum what JS can represent in integer precisely.

Alternatively you can count in floats from the very start by adding (letter_index / 64letter_position) for each position in line, but you'd be losing more precision in process.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
  • 1
    A computer display can only make use of 2^24 distinct colors anyway so the limited precision isn't really an issue. Wonder if you need to work with a float for the color anyway, you could just do the maths in modulo 2^24 and not have to worry about the integer overflowing. – millimoose Jun 27 '12 at 12:05
  • Thanks Oleg. Appreciate your help. – Derek Hill Jun 27 '12 at 19:52