Bitwise and in PHP

I am a very new person to PHP. I read that it dechex(255)will provide the corresponding hexadecimal value ffin PHP.

I need a hex value -105. I tried dechex(-105)and got the result as ffffff97. But I just want to 97do some things.

In Java, I know that a little work with 0xffgave us the result 97, which (byte)-105 & (byte)0xff = 0x97.

Please find a solution in PHP just like I did in Java.

+4
source share
3 answers

You can do it in php as follows:

var_dump(dechex(-105 & 255))

to output it from the final byte (example below)

string(2) "97"
+1
source

dechex() 0 2 * PHP_INT_MAX + 1 (unsigned int).

, 0 2 * PHP_INT_MAX + 1, .

-105 0xffffff97, 0x97

0xffffff97 - 4294967191. 0x97 151.

, , abs().

$abs = abs(-105); // $abs becomes +105
$hex = dechex($abs); // $hex becomes 69
+1

Either you want a binary negative value (ffffff97) or a signed value

// for a signed value
$i = -105;
if($i < 0)
     echo '-'.dechex(abs($i));
else echo dechex($i);

If you want to remove the front "f"

echo preg_replace('#^f+#', '', dechex($i));
0
source

All Articles