How to convert Long types in JavaScript?

I know there is no Long type in JavaScript, but how can I convert the corresponding bytes bytecode to Long type? Here is a piece of java code that can be easily converted in java, such as

byte [] a = {0x02,0x03, 0x04, 0x05, 0x06,0x07, 0x08, 0x09};
public static long bytesToLong( byte[] array ) {
        if(array.length==0) return 0;
        return ((((long) array[ 0] & 0xff) << 56)
                | (((long) array[ 1] & 0xff) << 48)
                | (((long) array[ 2] & 0xff) << 40)
                | (((long) array[ 3] & 0xff) << 32)
                | (((long) array[ 4] & 0xff) << 24)
                | (((long) array[ 5] & 0xff) << 16)
                | (((long) array[ 6] & 0xff) << 8)
                | (((long) array[ 7] & 0xff) << 0)
        );
    }

the final output of the above code in java is: 144964032628459529

I tried to use JavaScript"s Uint8Array and ArrayBuffer to write a corresponding method. I used parseFloat to convert the array [] array, but it didn"t succeed. The following code outputs 101125133. What should I do if JavaScript doesn"t have Long type conversion? Wang Dashen gives advice

    let bcd = new Uint8Array(8)
        bcd[0] = 0x02
        bcd[1] = 0x03
        bcd[2] = 0x04
        bcd[3] = 0x05
        bcd[4] = 0x06
        bcd[5] = 0x07
        bcd[6] = 0x08
        bcd[7] = 0x09
function bytesToLong(array) {
        if (array.length === 0) return 0
        return (((array[0] & 0xff) << 56)
            | ((array[1] & 0xff) << 48)
            | ((array[2] & 0xff) << 40)
            | ((array[3] & 0xff) << 32)
            | ((array[4] & 0xff) << 24)
            | ((array[5] & 0xff) << 16)
            | ((array[6] & 0xff) << 8)
            | ((array[7] & 0xff) << 0))
    }
bytesToLong(bcd)
//101125133


js does not have long or short integers. If a numerical type


cannot be converted, it depends on your actual needs to workaround


.

js does not have long , only number of 64-bit IEEE754 standard. You can map number to long , or you can just save it. Write a wrapper class to implement four operations, and use Uint32Array of length 2 instead.

< hr >

just know that there is a new BigInt , which should be used if your target runtime supports it.


if the JS integer exceeds 2 ^ 53-1, it is no longer accurate, and the JS median operation is calculated according to 32 bits, so it cannot be calculated directly.

can be converted using BigInt of Stage 3 or other large number libraries.


replace the Number type with BigInt, the code is as follows:

  https://github.com/GoogleChro. substitution; of course, you can also use two Number types to encapsulate BigInt or Long types. You have to define addition, subtraction, multiplication, division, OR, and so on, and the workload is not small. You can measure it yourself 

.
Menu