4

I am very new face to PHP. I read that dechex(255) will give the corresponding hex value ff in PHP.

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

In Java I know that a bit wise operation with 0xff gave us the result 97 that is (byte)-105 & (byte)0xff = 0x97.

Please to find the solution in PHP just like I've done in Java.

halfer
  • 19,824
  • 17
  • 99
  • 186
Arshad
  • 41
  • 2
  • That value is probably correct: bear in mind that `-1` is all bits set (all `f`s). These values are regarded as negative because the left-most bit is set. You'll find you get the same result in Java too. – halfer Mar 09 '15 at 11:57

3 Answers3

1

You can do it in php like this:

var_dump(dechex(-105 & 255))

to make it out of the final byte (example output below)

string(2) "97"
Nathan
  • 331
  • 2
  • 4
1

dechex() gives you a hexadecimal value for a decimal value between 0 and 2*PHP_INT_MAX+1 (unsigned int).

Anything below 0 or above 2*PHP_INT_MAX+1, will loop.

-105 is NOT 0xffffff97 , and it is not 0x97

0xffffff97 is 4294967191. and 0x97 is 151.

If you want the hexadecimal representation of the negative number turned into a positive number, use the function abs().

$abs = abs(-105); // $abs becomes +105
$hex = dechex($abs); // $hex becomes 69
nl-x
  • 11,762
  • 7
  • 33
  • 61
0

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 front "f"

echo preg_replace('#^f+#', '', dechex($i));
Kulvar
  • 1,139
  • 9
  • 22
  • 2
    That `if` statement doesn't do a lot on its own. If you meant for that to affect the following statement, remove the `;` -- and you should use braces anyway, to remove the ambiguity. – halfer Mar 09 '15 at 12:31