简体   繁体   中英

Trying to encode in base 64 a byte array from a BigInteger in javaScript

I am trying to implement the exact same java algorythm in javaScript :

String s = "6332878812086272"; // For example
long id = Long.valueOf(s);
final byte[] idBytes = BigInteger.valueOf(id).toByteArray();
final String idBase64 = Base64.getEncoder().encodeToString(idBytes);

Is this possible as javaScript does not handle big number like java BigInteger/long? Any libraries recommendations?

You can probably try something like that:

// number -> number in base 2 as string
var nbrAsBits = (6332878812086272).toString(2); //"10110 01111111 10111000 01000000 00000000 00000000 00000000"

// number in base 2 as string -> array of bytes (8 bits) as numbers
var nbrAsIntArray = convertionTool(nbrAsBits); //[22, 127, 184, 64, 0, 0, 0]

// array of bytes as numbers -> bytes
var nbrAsByteArray= new Uint8Array(bytes);

// concat everything in a string
var str = "";
for(var i=0; i<byteArray.length; i++) {
    str += String.fromCharCode(byteArray[i]);
}

// get the base64
btoa(str); //"Fn+4QAAAAA=="

You will have to implement the convertionTool() function which will convert every byte into its numerical value. Use the power of 2 like in this example:

01111111 = 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0 = 127

Note

The java long data type has a maximum value of 2^63 - 1 ( primitive data type ) while the javascript number has a maximum value of 2^53 - 1 ( Number.MAX_SAFE_INTEGER ).

So in javascript you won't be able to process number between 9007199254740991 2^63 - 1 and 9223372036854775807 2^53 - 1 , when in java you can.

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