PHP bitwise left shifting 32 spaces problem and bad results with large numbers arithmetic operations

前端 未结 3 835
甜味超标
甜味超标 2021-01-06 16:31

I have the following problems:

First: I am trying to do a 32-spaces bitwise left shift on a large number, and for some reason the number is always returned as-is. Fo

相关标签:
3条回答
  • 2021-01-06 16:44

    Doing 32 bit-shifting operations will probably not work like you expect, as integers tend to be stored on 32 bits.

    Quoting this page : Bitwise Operators

    Don't right shift for more than 32 bits on 32 bits systems.
    Don't left shift in case it results to number longer than 32 bits.
    Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.

    0 讨论(0)
  • 2021-01-06 16:56

    Php integer precision is limited to machine word size (32, 64). To work with arbitrary precision integers you have to store them as strings and use bc or gmp library:

       echo bcmul('516103988', bcpow(2, 32));  // 2216649749795176448
    
    0 讨论(0)
  • 2021-01-06 16:57

    Based on Pascal MARTIN's suggestions, i tried both the BCMath and the GMP extension and came up with the following solutions:

    With BCMath:

    $a = 516103988;
    $s = bcpow(2, 32);    
    $a = bcadd(bcmul($a, $s), 9379);
    echo $a; // works, echoes 2216649749795185827
    

    With GMP:

    $a = gmp_init(516103988); 
    $s = gmp_pow(gmp_init(2), 32); 
    $a = gmp_add(gmp_mul($a, $s), gmp_init(9379)); 
    echo gmp_strval($a);  // also works
    

    From what i understand, there is a far greater chance for BCMath to be installed on the server then GMP, so i will be using the first solution.

    Thanks :)

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