Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

right shift >> turns value into zero javascript

Trying some bit manipulation in javascript.

Consider the following:

const n = 4393751543811;
console.log(n.toString(2)) // '111111111100000000000000000000000000000011'
console.log(n & 0b11) // last two bits equal 3
const m = n >> 2; // right shift 2
// The unexpected.
console.log(m.toString(2)) // '0'

The result is 0? The expected output I am looking for after the right shift is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

111111111100000000000000000000000000000011 // pre
001111111111000000000000000000000000000000 // post >> 

How is this accomplished?

>Solution :

Javascript bitwise operators on numbers work "as if" on 32bit integers.

>> (sign-propagating right-shift for numbers) will first convert to a 32-bit integer. If you read linked spec, note specifically

Let int32bit be int modulo 232.

In other words, all bits above 32 will simply be ignored. For your number, this results in the following:

111111111100000000000000000000000000000011
┗removed━┛┗━━━━━━━━━━━━━━32bit━━━━━━━━━━━━━┛

If you want, you can use BigInt:

const n = 4393751543811n; // note the n-suffix
console.log(n.toString(2))
console.log(n & 0b11n) // for BigInt, all operands must be BigInt
const m = n >> 2n;
// The expected.
console.log(m.toString(2))

The spec for >> on BigInt uses BigInt::leftShift(x, -y), where it in turn states:

Semantics here should be equivalent to a bitwise shift, treating the BigInt as an infinite length string of binary two’s complement digits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading