Unsigned Integer in Javascript

前端 未结 6 887
梦谈多话
梦谈多话 2020-11-27 03:28

I\'m working on a page that processes IP address information, but it\'s choking on the fact that integers are signed. I am using bitwise operators to speed it up, but the 64

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 03:40

    document.write( (1 << 31) +"
    ");

    The << operator is defined as working on signed 32-bit integers (converted from the native Number storage of double-precision float). So 1<<31 must result in a negative number.

    The only JavaScript operator that works using unsigned 32-bit integers is >>>. You can exploit this to convert a signed-integer-in-Number you've been working on with the other bitwise operators to an unsigned-integer-in-Number:

    document.write(( (1<<31)>>>0 )+'
    ');

    Meanwhile:

    document.write( (1 << 32) +"
    ");

    won't work because all shift operations use only the lowest 5 bits of shift (in JavaScript and other C-like languages too). <<32 is equal to <<0, ie. no change.

提交回复
热议问题