[removed] Bitwise shift of long long number

前端 未结 2 692
后悔当初
后悔当初 2020-11-28 10:24

I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after 32.

For example:

for(var j = 0; j < 64;          


        
相关标签:
2条回答
  • 2020-11-28 10:39

    "In Java, the bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow. JavaScript is rarely used for doing bit manipulation." - Douglas Crockford, Javascript: The Good Parts

    The point is that you don't really have any reason to use bitwise operators. Just multiply or divide by 2^numbits.

    Your code should be:

    for(var j = 0; j < 64; j++) {
     mask = mask * 2;
     console.log(mask);
    }
    

    Or generally:

    function lshift(num, bits) {
        return num * Math.pow(2,bits);
    }
    

    You get the idea.

    0 讨论(0)
  • 2020-11-28 10:42

    JavaScript stores all its numbers as 64 bit initally, but as soon as you start using bitwise operators the interpreter converts the number to a 32 bit representation..

    Bitwise operators are a bit hacky in JS and so annoyingly you will probably have to do something a bit more clever, like write your own 64 bit functions.

    0 讨论(0)
提交回复
热议问题