Javascript [SOLVED]: What exactly does shift operation whose right operand is over 31 do, in Javascript?

Javascript [SOLVED]: What exactly does shift operation whose right operand is over 31 do, in Javascript?

Home Forums Scripting Javascript Tutorials Javascript [SOLVED]: What exactly does shift operation whose right operand is over 31 do, in Javascript?

Tagged: 

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245679

    Cloudy Point
    Keymaster

    QuestionQuestion

    I know that operands of bitwise operation are treated as 32-bit integers in Javascript. So I thought that it would be zero’d out if I do << 32 on integer values. But it worked as if it’s << 0. For what reason is it worked in that way? What exactly does shift operation whose right operand is over 31 do, in Javascript?

    0b00000000000000000000000000000001 << 32 // 1
    0b00000000000000000000000000000001 << 33 // 2
    0b00000000000000000000000000000001 << 34 // 4
    
    0b00000000000000000000000000000001 >> 30 // 0
    0b00000000000000000000000000000001 >> 31 // 0
    // Something weird is happening.......
    0b00000000000000000000000000000001 >> 32 // 1
    0b00000000000000000000000000000001 >> 33 // 0
    

    #245680

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    It truncates the binary representation of the right operand.

    From the documentation for 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.

    So in your example, 32 is 0b100000. Since it only takes the lowest five bits you’re left with 0b00000, so it shifts the number by 0. Again, 33 is 0b100001 and the lowest five bits are 0b00001, so it shifts the number by 1. And so on.

    Source: https://stackoverflow.com/questions/48014822/what-exactly-does-shift-operation-whose-right-operand-is-over-31-do-in-javascri
    Author: Herohtar
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.