对于编码,Javascript从标准的Anscii表中提取字符进行映射。我发现下面的function可以很好地正确地编码为Anscii85/Base85。但是我想编码成Z85变体,因为它包含了我需要的一组符号。我的理解是,Ansii85 /Base85编码的工作原理应该完全相同,除了Z85以不同于Anscii标准的顺序映射值,并使用来自标准Base85映射的不同符号组合。所以字符集是唯一的区别:
Ansci85使用从32到126 (reference)的85个字符:"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu
Z85使用85个字符的自定义集(reference):0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#
我的问题是,有没有办法重新定义charCodeAt和fromCharCode在这个函数中引用的字符集,以便它可以在Z85中编码?
// By Steve Hanov. Released to the public domain.
function encodeAscii85(input) {
// Remove Adobe standard prefix
// var output = "<~";
var chr1, chr2, chr3, chr4, chr, enc1, enc2, enc3, enc4, enc5;
var i = 0;
while (i < input.length) {
// Access past the end of the string is intentional.
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
chr4 = input.charCodeAt(i++);
chr = ((chr1 << 24) | (chr2 << 16) | (chr3 << 8) | chr4) >>> 0;
enc1 = (chr / (85 * 85 * 85 * 85) | 0) % 85 + 33;
enc2 = (chr / (85 * 85 * 85) | 0) % 85 + 33;
enc3 = (chr / (85 * 85) | 0 ) % 85 + 33;
enc4 = (chr / 85 | 0) % 85 + 33;
enc5 = chr % 85 + 33;
output += String.fromCharCode(enc1) +
String.fromCharCode(enc2);
if (!isNaN(chr2)) {
output += String.fromCharCode(enc3);
if (!isNaN(chr3)) {
output += String.fromCharCode(enc4);
if (!isNaN(chr4)) {
output += String.fromCharCode(enc5);
}
}
}
}
// Remove Adobe standard suffix
// output += "~>";
return output;
}额外说明:
或者,我认为我可以使用类似下面的function,但问题是它一开始就没有正确地编码Anscii85。如果它是正确的,Hello world!应该编码为87cURD]j7BEbo80,但此函数将其编码为RZ!iCB=*gD0D5_+ (reference)。
我对算法的理解不够深入,无法知道这里的映射出了什么问题。理想情况下,如果编码正确,我应该能够更新此函数以使用Z85字符集:
// Adapted from: Ascii85 JavaScript implementation, 2012.10.16 Jim Herrero
// Original: https://jsfiddle.net/nderscore/bbKS4/
var Ascii85 = {
// Ascii85 mapping
_alphabet: "!\"#$%&'()*+,-./0123456789:;<=>?@"+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"+
"abcdefghijklmnopqrstu"+
"y"+ // short form 4 spaces (optional)
"z", // short form 4 nulls (optional)
// functions
encode: function(input) {
var alphabet = Ascii85._alphabet,
useShort = alphabet.length > 85,
output = "", buffer, val, i, j, l;
for (i = 0, l = input.length; i < l;) {
buffer = [0,0,0,0];
for (j = 0; j < 4; j++)
if(input[i])
buffer[j] = input.charCodeAt(i++);
for (val = buffer[3], j = 2; j >= 0; j--)
val = val*256+buffer[j];
if (useShort && !val)
output += alphabet[86];
else if (useShort && val == 0x20202020)
output += alphabet[85];
else {
for (j = 0; j < 5; j++) {
output += alphabet[val%85];
val = Math.floor(val/85);
}
}
}
return output;
}
};发布于 2019-03-14 10:33:07
字符代码是字符代码。您不能更改String.fromCharCode()或String.charCodeAt()的行为。
但是,您可以将自定义字符集存储在数组中,并使用数组索引和Array.indexOf()查找条目。
不过,更新此函数以使用Z85将很棘手,因为String.fromCharCode()和String.charCodeAt()在两个不同的上下文中使用--它们有时用于访问未编码的字符串(不需要更改),而有时用于已编码的字符串(需要更改)。您需要注意不要混淆这两者。
https://stackoverflow.com/questions/55153980
复制相似问题