I got an array which is 32 bit, big endian unsigned integers, basically in plain text is like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
That 32bit endian array itself is encoded in binary base64 AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==
Initially, if I receive this from heaven, now how can I decode/unpack everything to that understandable plain text representation in JavaScript.
In ruby I can simply use Base64.decode
and 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]
Is there an equivalent of this simple step in JavaScript?
You could decode the given string and take onyl four characters for convering to a 32 bit number by using ArrayBuffer
and 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; }