Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to byte in PHP

Tags:

php

casting

byte

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?

like image 388
shay Avatar asked Jul 29 '10 10:07

shay


2 Answers

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.

like image 110
mvds Avatar answered Sep 20 '22 10:09

mvds


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
like image 25
Piotr Müller Avatar answered Sep 19 '22 10:09

Piotr Müller