John Davidson

Bit shifting in C is different from PHP

0 comments
Message:


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


My Answer:
The issue here is with the way bit shifting is handled in C versus PHP. In C, the << operator is used for left shifting bits, while in PHP, the << operator is used for concatenation.

To achieve the same result in PHP as in the C code provided, you can use the bitwise shift operators >> and << for left and right shifting respectively.

Here is the corrected PHP code:

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


This should give you the same result as the C code.

Rate this post

5 of 5 based on 7995 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us