我创建了一个Java程序,使用Java的BigInteger类为我提供所需的输出。
String key = "253D3FB468A0E24677C28A624BE0F939";
byte[] array = new BigInteger(key, 16).toByteArray();
System.out.println(Arrays.toString(array));
使用以下输出:
[37,61,63,-76,104,-96,-30,70,119,-62,-118,98,75,-32,-7,57]
尝试使用JavaScript进行相同操作。使用Big Int库:https://github.com/peterolson/BigInteger.js因为十六进制值太长。
var q = new bigInt("253D3FB468A0E24677C28A624BE0F939", 16);
console.log(q.toString());
var out = q.toString();
var bytes = [];
for (var i = 0; i < out.length; ++i) {
var code = out.charCodeAt(i);
bytes = bytes.concat([code]);
}
console.log(bytes);
bytes = [52,57,52,57,57,52,53,56,48,51,55,54,54,55,55,51,50,49,49,50,56,56, 51,55,53,48,53,50,54,55,57,52,49,51,53,56,54,53]
如何使用JavaScript获得相同的Java输出?非常感谢
答案 0 :(得分:1)
您不需要图书馆。只需解析出每个字节并将其添加到数组中(通过一些操作来模仿Java的带符号字节):
var q = '253D3FB468A0E24677C28A624BE0F939';
var bytes = [];
for (var i = 0; i < q.length; i += 2) {
var byte = parseInt(q.substring(i, i + 2), 16);
if (byte > 127) {
byte = -(~byte & 0xFF) - 1;
}
bytes.push(byte);
}
console.log(bytes);
// [37, 61, 63, -76, 104, -96, -30, 70, 119, -62, -118, 98, 75, -32, -7, 57]
答案 1 :(得分:1)
试试这个:
var input = "253D3FB468A0E24677C28A624BE0F939";
var output = "";
for (var i = 0; i < input.length; i += 2) {
var value = parseInt(input.substr(i, 2), 16);
output += ", " + (value < 128 ? value : value - 256);
}
output = "[" + output.substr(2) + "]";
答案 2 :(得分:1)
您可以使用自定义转化,将numbers > 127
调整为负数。
var key = "253D3FB468A0E24677C28A624BE0F939",
bytes = key.match(/../g).map(function (a) {
var i = parseInt(a, 16)
return i >> 7 ? i - (1 << 8) : i;
});
console.log(bytes);
&#13;