PHP 右移结果为负?
我在将一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题是 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 hasinteger
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).