我有一个字节数组,我在Android设备上生成,编码为base64,发送到服务器,然后使用JavaScript在Web上显示。但是字节数组不匹配。
示例字节数组:
-39,86,-91,26,77,98,-3,108,83,-108,-53,-8,-102,-39,-42,-106,-90,70,122,26,43,-46,82,124,-4,-116,-51,-92,100,-104,57,9,-127,0
android side encoding:
import android.util.Base64;
Base64.encodeToString(byteArray, Base64.DEFAULT);
结果字符串:
2ValGk1i/WxTlMv4mtnWlqZGehor0lJ8/IzNpGSYOQmBAA==
javascript解码:
var decoded = atob(encodedString);
var bytes = [];
for (var i = 0; i < decoded.length; i++) {
bytes.push(decoded.charCodeAt(i));
}
结果字节数组:
217,86,165,26,77,98,253,108,83,148,203,248,154,217,214,150,166,70,122,26,43,210,82,124,252,140,205,164,100,152,57,9,129,0
所有应为负数的数字都添加了256个。我该如何解决这个问题?
注意:解码它的android端会产生预期的结果。
答案 0 :(得分:0)
我通过在循环内手动纠正它解决了这个问题:
for (var i = 0; i < decoded.length; i++) {
var currentChar = decoded.charCodeAt(i);
if (currentChar < 128)
bytes.push(currentChar);
else
bytes.push(currentChar - 256);
}
我仍在寻找实现这一目标的正确方法,如果有人知道请发帖。