Bitwise operations on 32-bit unsigned ints?

后端 未结 3 831
滥情空心
滥情空心 2020-12-04 15:38

JavaScript converts operands to 32-bit signed ints before doing bitwise operations. It also does the operation with 32-bit signed ints, meaning that the result is a 32-bit s

相关标签:
3条回答
  • 2020-12-04 16:04

    It's ugly, but:

    var a = 1986735448;
    var b = (a << 1) >>> 0;
    /* b = 3973470896 */
    
    0 讨论(0)
  • 2020-12-04 16:09

    You only have to follow these rules:

    1. always end bit wise ops with >>> 0 so the result gets interpreted as unsigned.
    2. don't use >>. If the left-most bit is 1 it will try to preseve the sign and thus will introduce 1's to the left. Always use >>>.

    Examples:

    C:  (3774191835 >> 2) | 2147483648
    js: (3774191835 >>> 2 | 2147483648) >>> 0
    
    C:  1986735448 << 1
    js: (1986735448 << 1) >>> 0
    
    C:  3774191835 & 4294967295
    js: (3774191835 & 4294967295) >>> 0
    

    Only if the last op is >>>, >>> 0 is not necessary.

    0 讨论(0)
  • 2020-12-04 16:15

    JavaScript takes care of this problem by offering two bit shift operators, >> and >>>. You want >>> to do a shift without shifting the sign bit.

    0 讨论(0)
提交回复
热议问题