How to split a 64-bit integer into two 32-bit integers

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

var bigInt = 0xffffff; var highInt = bigInt >> 8 // get the high bits 0xfff var lowInt = bigInt // cut of the first part (with &)? console.log(highInt); // 0xfff console.log(lowInt); // 0xfff // set them together again var reBigInt = (highInt << 8) + lowInt; 

Unfortunately, neither getting highInt nor getting lowInt work ... Can someone give me an answer on how I need to use bitwise operators?

considers

+6
source share
2 answers

EDIT JavaScript represents integers using the IEEE double-precision format , so there is no way to store arbitrary 64-bit integers without loss of precision, except for specialized large integer libraries. Bitwise operations with potentially truncated values ​​obviously do not make sense.


In general, for languages ​​that support 64-bit integers:

The 64-bit template of them is 0xffffffffffffffff . To extract the top 32 bits, you need to shift by 32: >> 32 . To extract the bottom 32 bits, just them with 32: & 0xffffffff .

You have the principle right - your arithmetic about how many bits are shifted or masked is simply not true.

+5
source

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

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

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

The reason is that we use the binary operator for any number - Javascript first converts that number to a 32-bit signed number, applies the binary operation, and returns the result. This means that any bit that is higher than 32 will be discarded.

I used the following approach to extract the higher (21 bits) and lower (32 bits) parts 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 the logic above is correct, try building a large two-part number

 Assert((lowInt * Math.pow(2, 32) + highInt) === bigNumber); 
+2
source

All Articles