In Java, I can easily cast a number to a byte, for example:
System.err.println((byte) 13020);
the result will be
-36
Now how can I achieve the same in PHP?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With