...trovata alla Alex. L'ufficio complicazione affari semplici in azione: codifica in base 59 di una stringa UTF-8, con l'esclusione dei codici di formattazione nella zona bassa (primi 26 codici). Anche i codici da 27 a 31 sono di formattazione, pero` ne ho esclusi esattamente 26 perche` con massimo 255-26 = 229 codici posso ancora rappresentare un numero di tre cifre (caratteri in ingresso) in base 229 con quattro cifre in base 59. E magari in futuro uno potrebbe usare i codici da 27 a 31 come sequenze di escape o marcatori di qualche genere.
var Base59 = {
t: [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
],
encode: function (s) {
var i, j, k, c, d, e, f, m;
var l = s.length;
var r = '';
for (i = 0, j = 1, k = 2; i < l; i += 3, j += 3, k += 3) {
c = s.charCodeAt (i) - 26;
d = j < l ? s.charCodeAt (j) - 26 : 0;
e = k < l ? s.charCodeAt (k) - 26 : 0;
m = 52441 * c + 229 * d + e;
c = Math.floor (m / 205379);
d = Math.floor (m / 3481) % 59;
e = Math.floor (m / 59) % 59;
f = m % 59;
r = r + this.t [f] + this.t [e] + this.t [d] + this.t [c];
}
return r;
},
decode: function (s) {
var i, j, k, h, c, d, e, f, m;
var l = s.length;
var r = '';
for (i = 0, j = 1, k = 2, h = 3; i < l; i += 4, j += 4, k += 4, h += 4) {
c = this.t.indexOf (s.charAt (i));
d = j < l ? this.t.indexOf (s.charAt (j)) : 0;
e = k < l ? this.t.indexOf (s.charAt (k)) : 0;
f = h < l ? this.t.indexOf (s.charAt (h)) : 0;
m = 205379 * f + 3481 * e + 59 * d + c;
c = Math.floor (m / 52441);
d = Math.floor (m / 229) % 229;
e = m % 229;
r = c ? r + String.fromCharCode (c + 26) : r;
r = d ? r + String.fromCharCode (d + 26) : r;
r = e ? r + String.fromCharCode (e + 26) : r;
}
return r;
}
}
console.log (Base59.encode ('If My Grandmother Had Wheels It Would Be A Cart'));
console.log (Base59.decode (Base59.encode ('If My Grandmother Had Wheels It Would Be A Cart')));
Output:
735cby7d8JzbokwmesNmXDej2FPb4qA1MPdj0bJn4fZnbwNmqcUieg9jj6z1pCyn
If My Grandmother Had Wheels It Would Be A Cart
Perche`? Perche` voglio far passare i dati da un formato che non dia mai problemi con caratteri speciali (inclusi i + e = della tipica codifica in base 64), depositabile direttamente in metodi GET e POST senza urlencoding, o in un DB SQL senza incorrere in injections, o in un nome di file, eccetera. E neanche che dia problemi di ambiguita` dei caratteri quando si leggono a occhio, quindi gia` che c'ero (con una base non piu` potenza di 2) ho escluso anche la i maiuscola, la o maiuscola e la elle minuscola.
Adesso mi offenderanno pesantemente.
**Modificato dall'autore il 24.03.2013 23:40**