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
).
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.
Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With