Search code examples
javascriptphpbit-manipulationbitwise-operatorsbit-shift

How can I implement a JS-style bitwise left shift operator in PHP?


I am trying to currently bitwise shift values in PHP in comparison to how the result would be in JavaScript. I have tried over solutions in stackoverflow and I have not been able to get it work currently how I would like it to. I am currently running PHP 7.1.

For example in a JS environment such as Chrome WebTools Console running this

var testValue = 94427771; (testValue << 5)

Results in: -1273278624

Whereas in PHP similar produces the following:

$testValue = 94427771; $testValue = ($testValue << 5); echo $testValue;

The output is: 96694037504

I've also tried this function which was posted on stackOverflow

function shift_left_32( $a, $b ) { return ( $c = $a << $b ) && $c >= 4294967296 ? $c - 4294967296 : $c; }

Where when you run the code shift_left_32($testValue, 5); It returns the value: 3021688672

How could I go about resolving this please. Thank you.


Solution

  • If you would like to restrict the return value of your bitwise shift to a 32bit signed integer then what you can do is modulo the number to max 32bit signed int and then overflow it.

    function shift_left_32( $a, $b ) {
        return ( $c = $a << $b ) && $c > 0x7FFFFFFF ? ($c % 0x80000000)-0x80000000 : $c;
    }
    

    or simpler and more correct with bitwise or:

    function shift_left_32( $a, $b ):int {
        return ( $a << $b ) | -0x80000000;
    }
    

    For more information you can take a look at this question: Convert from 64bit number to 32bit number