开发者

Convert number to byte in PHP

In Java, I can easily cast a number to a byte, for example:

System.err.println((byte) 13020);
开发者_如何学JAVA

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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜