Convert php to bytes,

In Java, I can easily write a number in bytes, for example:

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

the result will be

 -36 

Now, how can I achieve the same in PHP?

+4
source share
3 answers

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

 $val = ($val % 256) - 128 

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

Edit: on the right, 0 will be 128, so maybe this solution will work:

 $val = (($val+128) % 256) - 128 
+2
source
 echo ($a&0x7f) + ($a&0x80?-128:0); 

change , this mimics what should happen for a signed 8-bit value. When the MSB (bit 7) is zero, we simply have the value of these 7 bits. When the MSB is set to 1, we start with -128 (i.e., 1000000b == -128d ).

You can also use the fact that PHP uses integer values โ€‹โ€‹inside:

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

so you shift the MSB byte to the MSB position for int, as php sees, i.e. you add 56 zero bits to the right. The section "deletes" these bits, preserving the sign of the value.

+6
source

You can not. PHP does not have a byte data type, such as Java.

0
source

All Articles