peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

Method to byteArray #103

Closed snatvb closed 7 years ago

snatvb commented 7 years ago

Do u have such method? Or how i can do it?

peterolson commented 7 years ago

You can convert a bigInt to hex, split it up into groups of two characters, and then create a byte array from that:

function toByteArray(x) {
    var hexString = x.toString(16);
    if(hexString.length % 2 > 0) hexString = "0" + hexString;
    var byteArray = [];
    for(var i = 0; i < hexString.length; i += 2) {
        byteArray.push(parseInt(hexString.slice(i, i + 2), 16));
    }
    return byteArray;
}

For example:

toByteArray(bigInt("456742343535"))
> [106, 87, 247, 19, 111]
snatvb commented 6 years ago

I'm so did it, thx, I was hoping on more fast resolve (sry, what i not answered to you promptly)

0xWhiteleaf commented 6 years ago

Is there a "fromArray" alternative ?

peterolson commented 6 years ago

@Zaliro Sorry, I'm not sure I understand what you're asking?

0xWhiteleaf commented 6 years ago

It's ok i've found by myself ! Thanks for your quick answer.