Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left-shift numbers greater than 32-bits? [duplicate]

As I understand it, JS treats numbers as 32-bits when performing bit-shift operations, even though it supports 64-bit numbers.

How can I implement a leftShift function that works on 64-bit numbers? i.e., it won't roll over into the negatives for something like 192 << 24 (should be 3221225472, not -1073741824).

like image 869
mpen Avatar asked Oct 14 '15 23:10

mpen


People also ask

How do you multiply by bit shifting?

To multiply a number, a binary shift moves all the digits in the binary number along to the left and fills the gaps after the shift with 0: to multiply by two, all digits shift one place to the left. to multiply by four, all digits shift two places to the left.

What does >> mean in C?

Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.

What does bit shifting by 1 do?

Bitshifting shifts the binary representation of each pixel to the left or to the right by a pre-defined number of positions. Shifting a binary number by one bit is equivalent to multiplying (when shifting to the left) or dividing (when shifting to the right) the number by 2.


1 Answers

Just do what the math of a left shift does:

Arithmetic shifts are equivalent to multiplication by a positive (to the left) or by a negative number (to the right), integral power of the radix (e.g. a multiplication by a power of 2 for binary numbers).

function shift(number, shift) {
    return number * Math.pow(2, shift);
}

shift(192, 24)
//3221225472

shift(3221225472, -24)
//192
like image 69
dave Avatar answered Sep 27 '22 18:09

dave