如何强制 PHP 将数字视为 uint
我有一些 C# 代码,如下所示:
uint a = 0x9E3779B9;
a += (uint)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24));
在该代码之后, a == 228 452 386
现在我尝试将此 C# 代码转换为 PHP,但在 PHP 中,数字不会以同样的方式溢出:
$a = 0x9E3779B9;
$a += ($url[$k+0] + ($url[$k+1] << 8) + ($url[$k+2] << 16) + ($url[$k+3] << 24));
在该代码之后, $a == 4 523 419 682
在这两种情况下,“url”都被视为 ascii 值数组。返回相同的结果,直到 $a 添加到第二行的结果中。此时,C# uint 溢出到约 2.28 亿。 PHP 变得“聪明”并给出了“正确”的答案。
但我想要 C# 给出的溢出答案。我应该怎么办?
I have some C# code that looks like this:
uint a = 0x9E3779B9;
a += (uint)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24));
After that code, a == 228 452 386
Now I'm trying to translate this C# code to PHP, but in PHP the number doesn't overflow the same way:
$a = 0x9E3779B9;
$a += ($url[$k+0] + ($url[$k+1] << 8) + ($url[$k+2] << 16) + ($url[$k+3] << 24));
After that code, $a == 4 523 419 682
In both cases "url" is treated as an array of ascii values. The returns the same results until the moment $a is added to the result of the second line. At that point, the C# uint overflows to ~228 million. PHP gets "clever" and comes up with the "right" answer.
But I want the overflowed answer that C# gives. What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
完成
+=
后,添加$a &= 0xFFFFFFFF
将值放回到 32 位范围内。(请参阅:http://www.ideone.com/6BR0U)
Add a
$a &= 0xFFFFFFFF
to put the value back into the 32-bit range after you've done the+=
.(See: http://www.ideone.com/6BR0U)
已经有一段时间了,工作答案已经提交,但我只是想强调一种更简单的方法来执行您正在做的解包:
我正在使用
unpack()
执行从二进制到 uint32(机器字节顺序)的转换。在 32 位平台上,最终结果可能会变为负数,这就是为什么我还使用printf()< /code>
正确格式化结果。
It has been a while and a working answer has already been submitted, but I just wanted to highlight an easier way to perform the unpacking that you're doing:
I'm using
unpack()
to perform the conversion from binary to uint32 (machine byte order). On 32-bit platforms, the end-result may become negative, which is why I'm also usingprintf()
to properly format the result.