1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | //------------------------------------------------------------------------------------------------ // Engines JavaScript 1.3+ // JScript 5.5+ // Environments NN4.06+ IE5.5+ MOZILLA1+ SAFARI1+ //------------------------------------------------------------------------------------------------ var Coding = { Num: { codec : '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_' , getBlockSize : function (b /* radix [2..63] */ ) { if (b == 2) b = 8; else if (b == 3) b = 6; else if (b > 3 && b < 7) b = 4; else if (b > 6 && b < 16) b = 3; else b = 2; return b; } //------------------------------------------------------------------------------------ , encode: function (n /* number */ , b /* radix [2..63] */ ) { var s = '' ; if (!isNaN(n) && !isNaN(b)) { if ( typeof n == 'string' ) n = parseInt(n); b = Math.min(Math.max(2, b), 63); do { s = this .codec.charAt(n % b) + s; n = Math.floor(n / b) } while (n > 0); n = Coding.Num.getBlockSize(b); b = s.length; while (b++ < n) s = '0' + s; } return s; } //------------------------------------------------------------------------------------ , decode: function (s /* src */ , b /* radix [2..63] */ ) { var n = 0; if (s != null && !isNaN(b)) { b = Math.min(Math.max(2, b), 63); for ( var i = 0, l = (s += '' ).length; i < l; ++i) n = n * b + this .codec.indexOf(s.charAt(i)); } return n; } } //----------------------------------------------------------------------------------------- , Base2x63: { encode: function (s /* src */ , b /* base [2..63] */ ) { var r = '' ; if (s != null && !isNaN(b)) { b = Math.min(Math.max(b, 2), 63); for ( var i = 0, l = (s += '' ).length; i < l; ++i) r += Coding.Num.encode(s.charCodeAt(i), b); } return r; } //------------------------------------------------------------------------------------ , decode: function (s /* src */ , b /* base [2..63] */ ) { var n, r = '' ; if (s != null && !isNaN(b)) { b = Math.min(Math.max(b, 2), 63); n = Coding.Num.getBlockSize(b); for ( var i = 0, l = (s += '' ).length; i < l; i += n) r += String.fromCharCode(Coding.Num.decode(s.substr(i, n), b)); } return r; } } }; |
1 2 3 4 5 6 7 8 9 10 | var e, s = 'Tomaré una decisión con la cigüeña.' ; for ( var i = 2; i < 64; ++i) { e = Coding.Base2x63.encode(s, i); alert ( 'base: ' + i + ', length: ' + e.length + ', encoded: ' + e + ', decoded: ' + Coding.Base2x63.decode(e, i) ); } |