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

Bitwise operations on large numbers

This works as expected:

> 0b1111
15
> 0b1111 & 0b1111
15

But this doesn’t:

> 0b11111111111111111111111111111111
4294967295
> 0b11111111111111111111111111111111 & 0b11111111111111111111111111111111
-1

What’s going on here? And how can I safely perform bitwise operations on large (up to 2^32) numbers in Javascript?

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

Update: This is below Number.MAX_SAFE_INTEGER so I don’t believe there should be a loss of precision.

>Solution :

What’s going on here?

JavaScript’s bitwise operators will interpret the result as a signed 32-bit number (one exception is the >>> operator), but apart from that, the result is correct.

And how can I safely perform bitwise operations on large (up to 2^32) numbers in Javascript?

Apply >>> 0 to the result so the result is interpreted as an unsigned 32 bit number:

let res = (0b11111111111111111111111111111111 
            & 0b11111111111111111111111111111111) >>> 0;

console.log(res);
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