开发者

PHP right shifting and negative result?

开发者 https://www.devze.com 2022-12-12 00:59 出处:网络
I\'ve run into a problem 开发者_开发百科whilst converting some C code to PHP, specifically in the use of the right-shift operator.

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?


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消