PHP 右移结果为负?

发布于 2024-08-11 16:06:28 字数 476 浏览 10 评论 0原文

我在将一些 C 代码转换为 PHP 时遇到了问题,特别是在使用右移运算符时。

编辑:在以下示例中,bit = 0;

原始 C 代码:

p->param->outBits[bytePtr++] |= codeword >> (9 + bit);

PHP 代码:

$outBits[$bytePtr++] |= $codeword >> (9 + $bit);

如果我以 codeword 为 130728 开始,在 CI 中得到的预期结果为 -1。在 PHP 中,我得到 255。我知道这与算术/逻辑移位差异有关,并且由于 MSB 保持为零而没有引入负号。

在 PHP 中是否有一种不涉及转换的“快速”方法来执行上述操作?例如,通过基本算术或类似的方法,这会给我预期的答案吗?

I've run into a problem whilst converting some C code to PHP, specifically in the use of the right-shift operator.

edit: in the following examples, bit = 0;

Original C code:

p->param->outBits[bytePtr++] |= codeword >> (9 + bit);

PHP code:

$outBits[$bytePtr++] |= $codeword >> (9 + $bit);

If I start with codeword being 130728, in C I get the expected result of -1. In PHP I get 255. I understand this is something to do with arithmetic/logical shift differences, and the negative sign not being introduced as a result of the MSBs staying at zero.

Is there a "quick" way of doing the above in PHP that doesn't involve the shifting? eg via basic arithmetic or similar, that will give me the expected answer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最舍不得你 2024-08-18 16:06:28

你的问题是 PHP 没有类型 byte,它只有 integer 通常是 32 位(而不是 8),所以如果你真的需要负值(无论如何,这些位都是正确的,因为无符号 255 与有符号 -1 相同),那么您可能应该添加缺少的 24 个或使用算术来恢复负值(255 是 -1,254 是 -2 等等,即 256 -x = -x)。

Your problem is that PHP doesn't have a type byte, it only has integer which usually is 32 bits (not 8), so if you really need negative value there (the bits are correct anyway, because unsigned 255 is the same as signed -1), then you should probably add the missing 24 ones or use arithmetics to restore the negative value (255 is -1, 254 is -2 and so on i.e. 256 - x = -x).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文