我试图在javaScript中实现完全相同的java algorythm:
String s = "6332878812086272"; // For example
long id = Long.valueOf(s);
final byte[] idBytes = BigInteger.valueOf(id).toByteArray();
final String idBase64 = Base64.getEncoder().encodeToString(idBytes);
这是否可行,因为javaScript不像java BigInteger / long那样处理大数字?任何图书馆建议?
答案 0 :(得分:0)
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
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.