简体   繁体   中英

Big Integer to Byte Array JavaScript

I made a Java program that gives me desired output using Java's BigInteger Class.

String key = "253D3FB468A0E24677C28A624BE0F939";
byte[] array = new BigInteger(key, 16).toByteArray();
System.out.println(Arrays.toString(array));

With the following output:

[37, 61, 63, -76, 104, -96, -30, 70, 119, -62, -118, 98, 75, -32, -7, 57]

Tried to make the same using JavaScript. Used a Big Int library: https://github.com/peterolson/BigInteger.js Because hex value is too long.

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]

How can I get same Java's output using JavaScript? Thanks a lot

You don't need the library. Just parse out each byte and add it to an array (with some manipulation to mimic Java's signed bytes):

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]

Try this:

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) + "]";

You could use a custom conversion which adjust numbers > 127 for negative numbers.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM