Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Converting code from C to PHP

    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 189
    Answer it

    Hi! I have a question about a small piece of code in C to make the same piece of code work in PHP, it has to do with a bit shift and I can't figure out what's wrong.

    C:
    unsigned u = 3910796769;
    u += u << 8;
    printf("%u\n",u); 
    //Result : 52422369

    PHP:
    $u = 3910796769;
    $u += $u << 8;
    printf("%u\n",$u);
    //Result : 1005074769633

 1 Answer(s)

  • It looks like the difference in results between the C and PHP code is due to how PHP handles integers and their sizes. In PHP, integers can have different sizes based on the system architecture, while in C, the size is typically fixed. This can lead to overflow issues.

    To make the PHP code produce the same result as the C code, you can use bitwise AND with a mask to limit the integer size:

    $u = 3910796769; $u += ($u << 8) & 0xFFFFFFFF; echo $u;

    Keep in mind that this solution is specific to handling the overflow issue in this particular scenario and may not apply to all cases. If you need assistance with more complex PHP development or have other questions, consider consulting a PHP website development company.

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: