tags:

views:

102

answers:

1

Hi,

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?

Thanks :-)

+1  A: 

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

inkredibl
That's what I was missing - see my comment above to @stereofrog. Cheers! :-)
richsage