how to split 64bit integer to two 32bit integers

前端 未结 2 902
夕颜
夕颜 2021-01-02 08:05

I want to split a 64bit integer into two 32bit integers:

var bigInt = 0xffffff;

var highInt = bigInt >> 8 // get the high bits 0xfff
var lowInt = bigI         


        
相关标签:
2条回答
  • 2021-01-02 08:31

    In JavaScript all numbers are represented using 53 bits. JavaScript uses floating point representation to store all numbers internally, which means that integers are stored as floating point numbers (mantissa has 53 bits)

    So with 53 bits we can represent max 2^53 = 9007199254740992.

    But you cannot use right shift and AND binary operations to extract lower 32 bits and higher 21 bits even from 53 bit numbers.

    The reason is when we apply binary operator on any number - Javascript first convert that number to 32 bit signed number, apply the binary operation and return the result. This means any bit that sits in position higher than 32 will be discarded.

    I have used following approach to extract the higher (21 bit) and lower (32 bits) portions from a positive number <= 2^53.

    var bigNumber = Math.pow(2, 53); // 9007199254740992
    var bigNumberAsBinaryStr = bigNumber.toString(2); // '100000000000000000000000000000000000000000000000000000'
    // Convert the above binary str to 64 bit (actually 52 bit will work) by padding zeros in the left
    var bigNumberAsBinaryStr2 = ''; 
    for (var i = 0; i < 64 - bigNumberAsBinaryStr.length; i++) {
        bigNumberAsBinaryStr2 += '0'; 
    }; 
    
    bigNumberAsBinaryStr2 += bigNumberAsBinaryStr;
    
    var lowInt = parseInt(bigNumberAsBinaryStr2.substring(0, 32), 2);
    var highInt = parseInt(bigNumberAsBinaryStr2.substring(32), 2);
    

    Just to confirm above logic is correct, lets try building the bigNumber from two parts

    Assert((lowInt * Math.pow(2, 32) + highInt) === bigNumber);
    
    0 讨论(0)
  • 2021-01-02 08:46

    EDIT JavaScript represents integers using IEEE double precision format, so there is no way to store arbitrary 64 bit integers without loss of precision, except through custom big integer libraries. Bitwise operations on potentially cropped values obviously make no sense.


    In general, for languages that do support 64 bit integers:

    A 64-bit pattern of ones is 0xffffffffffffffff. To extract the upper 32 bits, you need to shift by 32: >> 32. To extract the lower 32 bit, just and them with 32 ones: & 0xffffffff.

    You got the principle right - your arithmetic on how many bits to shift or mask is just wrong.

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