• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

218
Views
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:

111111111100000000000000000000000000000011 // pre
001111111111000000000000000000000000000000 // post >> 

How is this accomplished?

almost 3 years ago · Santiago Gelvez
1 answers
Answer question

0

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.

almost 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error