0

The case is the following:

/// returns 406913024, but should 417018740736
    alert(6363201 << 16); 

What is wrong? I tried the same in ruby and it returns the correct value (http://www.miniwebtool.com/bitwise-calculator/bit-shift/?data_type=10&number=6363201&place=16&operator=Shift+Left)

1
  • 3
    Javascript uses a 32-bit int internally. Commented Dec 17, 2013 at 12:33

2 Answers 2

4

Quoting from MDN Left Shift Operator

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

Quoting Bitwise Shift Operators

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.

Binary of 6363201 is 11000010001100001000001.

When you left shift 6363201 << 16, it becomes 417018740736 which in binary is 110000100011000010000010000000000000000

Now, 32 bits from the least significant bits are retained, the actual bits retained are 00011000010000010000000000000000 which corresponds to 406913024

Sign up to request clarification or add additional context in comments.

Comments

2

In JavaScript, you are dealing with 32-bit numbers.

6363201 << 16 results in 110000100011000010000010000000000000000, which are 39 bits. Shedding off the first 7 bits (since you are shifting from right to left, you end up with 00011000010000010000000000000000, which a (binary) parseInt of it will show you that is 406913024, not 417018740736.

2 Comments

I have the same problem with Typescript. How to get the right number back? Does this mean that we can not perform this operation in JS and TS?
@mor222, I believe you have to find other ways to do that operation. This is a good place to start, bot the article and its comments: 2ality.com/2012/07/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.