我有一个 32位的数组,大端无符号整数,基本上是纯文本的[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
那个 32位字节序数组本身是用二进制base64编码的AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==
最初,如果我从天堂收到这个,现在我怎么能解码/解压缩一切到JavaScript中可理解的纯文本表示。
在ruby中,我只需使用Base64.decode
和String#Unpack
encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='
decoded_string = Base64.strict_decode64(encoded_string)
=> "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\x00\x00\x00\b\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\v\x00\x00\x00\f\x00\x00\x00\r\x00\x00\x00\x0E\x00\x00\x00\x0F\x00\x00\x00\x10"
decoded_string.unpack('N*') #32-bit unsigned, network (big-endian) byte order
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
JavaScript中是否有这个简单的步骤。
答案 0 :(得分:1)
您可以使用ArrayBuffer
和DataView
function getInt(string) {
var view = new DataView(new ArrayBuffer(4)),
i;
for (i = 0; i < string.length; i++) {
view.setUint8(i, string.charCodeAt(i));
}
return view.getInt32(0);
}
var encodedData = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==',
decodedData = window.atob(encodedData),
result = [],
i = 0;
while (i < decodedData.length) {
result.push(getInt(decodedData.slice(i, i += 4)));
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
好的,经过一番严格的搜索,我发现这个图书馆特定于此目的 - https://www.npmjs.com/package/binary
还提供其他编码
encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='
let buffer = new Buffer(encoded_string, 'base64');
let arrayList = [];
let binaryList = binary.parse(buffer);
for (var i = 0; i <(buffer.length / 4); i++) {
arrayList.push(binaryList.word32bu('a').vars.a);
};