你的想法是正确的,只是 JavaScript 不能准确地表示那么大的数字。当您使用 parseInt 将其转换为 JavaScript 数字时,您的 170 位数字会失去其准确性;并不能逐位表示原来的数字。
解决方案很简单:滚动你自己的数字解析函数,将 170 位数字分成更小的块。
function encode(a) {
var b = "";
while (a.length > 0) {
b = parseInt(a.slice(-5), 2).toString(32) + b;
a = a.slice(0, -5);
}
return b;
}
function decode(a) {
var b = "";
while (a.length > 0) {
b = ("00000" + parseInt(a.slice(-1), 32).toString(2)).slice(-5) + b;
a = a.slice(0, -1);
}
return b;
}
var s = "00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000";
var e = encode(s); // "000lq2k8et1a45es002748kh2i4a0tp000"
var d = decode(e); // d === s
更通用的功能:
function convert(string, base1, base2) {
var result = "",
chunkw = 0, // number of characters to write per chunk
chunkr = 0, // number of characters to read per chunk
padstr = "", // string of zeros for padding the write chunks
slice;
while (Math.pow(2, chunkw) < base1) chunkw += 1;
while (Math.pow(2, chunkr) < base2) chunkr += 1;
while (padstr.length < chunkw) padstr += "0";
while (string.length > 0) {
slice = string.slice(-chunkr);
slice = parseInt(slice, base1).toString(base2);
slice = (padstr + slice).slice(-chunkw);
result = slice + result;
string = string.slice(0, -chunkr);
}
return result;
}
var x = "00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000";
var a = convert(x, 2, 32);
var b = convert(a, 32, 2);
console.log(x + "\n" + a + "\n" + b);
// 00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000
// 000lq2k8et1a45es002748kh2i4a0tp000
// 00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000