views:

59

answers:

3

in java i can cast number to byte for example

  System.err.println((byte)13020);

the result will be

-36

how can i do the same in php ?

+1  A: 

You can't. PHP has no byte data type like Java does.

Daniel Egeberg
don't tell me you can't do that in PHP. it might not be straightforward but it most definitely is doable.
Peter Perháč
@Peter: How do you cast to a data type that doesn't exist?
Daniel Egeberg
He doesn't care about the actual data type used. He wants the number handled as a byte-cast would in java
gnud
he doesnt ask you to CAST it, just convert it.
Peter Perháč
+2  A: 

Maybe do a modulo 256 expression (if unsigned) or modulo 256 and minus 128.

$val = ($val % 256) - 128

This work if you only want a value. If you want a real-one-byte, maybe pack() function will help here.

Edit: Right, 0 would be 128, so maybe this solution do will works:

$val = (($val+128) % 256) - 128
killer_PL
so... 0 will be -128? odd.
mvds
(13020 % 256) - 128 will not give back a -36 , i am getting -128 instead
shay
@shay: You should at least get `92` which is `-36` modulo `128`
Felix Kling
I saw this has become the accepted answer. However, there's still some nasty corner cases which are not handled propery. As an example, putting in `$val = -512;` gives the surprising result of `-256` instead of 0 (since -512 decimal == 0xfffffe00 in 32 bit) This is especially funny since -256 cannot be represented in 8 bits. So I'll make it explicit: **don't use the modulo operator to do bit operations**, ever. It's asking for trouble.
mvds
+4  A: 
echo ($a&0x7f) + ($a&0x80?-128:0);

edit this mimics what should actually happen for a signed 8-bit value. When the MSB (bit 7) is zero, we just have the value of those 7 bits. With the MSB set to 1, we start at -128 (i.e. 1000000b == -128d).

You could also exploit the fact that PHP uses integer values internally:

$intsize = 64; // at least, here it is...
echo ($a<<($intsize-8))/(1<<($intsize-8));

so you shift the MSB of the byte to the MSB position of the int as php sees it, i.e. you add 56 zero bits on the right. The division "strips off" those bits, while maintaining the sign of the value.

mvds
+1 Nice, but it would be better if you explain how it works.
Felix Kling
Better? included some more bit magic for fun.
mvds
working great :) thank you
shay