Confusion with the Left Changer

I am trying to create a 32 bit bitmask in JS. However, I do not understand what is going on here:

$ node
> const num = Math.pow(2, 31) - 1
undefined
> num
2147483647

# So far, so good
> num.toString(2)
'1111111111111111111111111111111'
> num.toString(2).length
31

# According to MDN, the left-shift operator does:
# "Excess bits shifted off to the left are discarded. 
#    Zero bits are shifted in from the right."
# But that not what we see here. Instead, it seems to be wrapping.
> num << 1
-2
> (num << 1).toString(2)
'-10'

In my understanding of MDN docs , I expect to have a bit mask of 31 1followed by 1 0. Instead, I get -10. What's going on here?

+4
source share
3 answers

Javascript does not Integer, but bitwise operators only make sense on Integer.

So, before bitwise operators, javascript will apply ToInt32(val)to your number.

For "Signed 32 bits Integer," the upper bit represents "signed."

Finally, your number overflows with the "signed bit".

, ECMAScript.

+1

. , . :

32- .

num 2147483647, :

01111111 11111111 11111111 11111111

num 1, :

11111111 11111111 11111111 11111110

32- -2 . , :

> num
2147483647
> num << 1
-2

toString(2) -2, toString(). :

  • . (-2 = > 2)
  • -2. (2 = > '10')
  • . ('10' = > '-10')

:

> (num << 1).toString(2)
> -10

:

> (-2).toString(2)
> -10
+1

Today I check your question again, and then I know that yesterday I misunderstood your main question.

This is your main question: "I expect to have a bit mask 31 1followed by 1. 0Instead, I get -10."

Because two additions .

A negative number does not express the value directly.

let num=Math.pow(2,31)-1
//num in memory=> 0111111111111111111111111111111
//                ^ 
//                |
//            signed bit
//This number is positive, so
//nothing to do=> 0111111111111111111111111111111

num = num<<1
//num in memory=> 1111111111111111111111111111110
//                ^ 
//                |
//            signed bit
//This number is negative, so flip then add 1
//flip         => 1000000000000000000000000000001
//add 1        => 1000000000000000000000000000010 => '-10'
0
source

Source: https://habr.com/ru/post/1692901/


All Articles