1

Javascript code:

console.log( 1 << 5 );
console.log( 1111044149 << 2 );

Javascript output:

32
149209300

PHP code:

var_dump( 1 << 5 );
var_dump( 1111044149 << 2 );

PHP output:

32
4444176596

Why 1111044149 << 2 has difference between PHP and javascript? I'm writing a javascript code to PHP and everything worked less that part and I need the PHP code shows similar results obtained in javascript to be perfect.

2
  • might be to large an integer for JS... Commented Apr 19, 2015 at 6:17
  • possible duplicate of Bitshift in javascript Commented Apr 19, 2015 at 6:22

2 Answers 2

3

The operands of a bitwise operation in JavaScript are always treated as int32, and in PHP this is not the case. So, when performing the left shift on 1111044149, this happens in JS:

01000010001110010011000000110101 (original, 32-bit)

00001000111001001100000011010100 (left shifted 2 positions, "01" is truncated)
= 149209300

And in PHP, the bits do not get truncated because it is not treated as a 32-bit integer.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, JS numbers are 64b floats. If the php output had been wrong, it would have been easy to explain due to overflow.
@Jite Indeed they are, but bitwise operations in JS work with 32-bit integers.
@ProgramFOX I had no idea of this. Thank you for info! :)
0

Thanks for the explanations, helped me a lot and I could now make a function to handle this automatically conversion, I had forgotten that detail about 32-bit and 64-bit for lack of attention.

Function

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

Test

var_dump( shift_left_32( 1, 5 ) );
var_dump( shift_left_32( 1111044149, 2 ) );

Output

32
149209300

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.