When I run this command in PHP, I get:
Code: 2269495617392648 >> 24
Result: 32
When I run it in C#.net or vb.net, I get:
Code: 2269495617392648 >> 24
Result: 135272480
PHP is correct.
The interesting thing is, that when I try to shift any number greater than int32 in .net, it yields bad results..
Every number under int32 (2147483647) yields the same results from php and c#.net or vb.net
Is there a workaround for this in .net?
Strictly speaking, PHP is wrong.
The entire bit pattern of the number
2269495617392648is:Right shifting this 24 times gets you:
This is the bit pattern for
135272480, not32.What’s going on in PHP apparently is that the number
2269495617392648is being truncated to538447880by perserving only the lower 32 bits. Note that the number2269495617392648is much too big to fit in a 32-bit integer, signed or unsigned.Right shifting the truncated bits 24 times gives us
32.You have alluded to this problem when you said:
It gives you bad results because some bits are being chopped off in order to fit in 32 bits.
If you’re porting from PHP to C# and need to preserve this behavior, you need to manually truncate the bits by using
2269495617392648 & 0xffffffffinstead of just2269495617392648(see jcomeau_ictx’s answer). But be aware that there is an issue of bit truncation going on in your PHP code. I’m not certain if it’s intentional or not.