shay
shay

Reputation: 1357

Convert number to byte in PHP

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?

Upvotes: 8

Views: 3875

Answers (3)

mvds
mvds

Reputation: 47034

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.

Upvotes: 7

Piotr M&#252;ller
Piotr M&#252;ller

Reputation: 5548

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

Upvotes: 3

Daniel Egeberg
Daniel Egeberg

Reputation: 8382

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

Upvotes: 0

Related Questions