Planning on sending integer values through as socket, I was surprised to find PHP only supports sending strings.
I came to the conclusion the only way to do it would be to create a string that would evaluate to the same byte values as the integer I wanted to send. So (after much messing about) I created a couple of functions: one to create this 'string' and one to convert a received value back to an integer.
<?php
function int2string($int, $numbytes=4)
{
$str = "";
for ($i=0; $i < $numbytes; $i++) {
$str .= chr($int % 256);
$int = $int / 256;
}
return $str;
}
function string2int($str)
{
$numbytes = strlen($str);
$int = 0;
for ($i=0; $i < $numbytes; $i++) {
$int += ord($str[$i]) * pow(2, $i * 8);
}
return $int;
}
echo int2string(16705, 2); echo string2int('AA'); ?>