1

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

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.