Voting

: eight plus zero?
(Example: nine)

The Note You're Voting On

davidccook+php at gmail dot com
16 years ago
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
//Converts an integer to 'byte array' (string), default to 4 'bytes' (chars)
function int2string($int, $numbytes=4)
{
$str = "";
for (
$i=0; $i < $numbytes; $i++) {
$str .= chr($int % 256);
$int = $int / 256;
}
return
$str;
}

//Converts a 'byte array' (string) to integer
function string2int($str)
{
$numbytes = strlen($str);
$int = 0;
for (
$i=0; $i < $numbytes; $i++) {
$int += ord($str[$i]) * pow(2, $i * 8);
}
return
$int;
}

//Example
echo int2string(16705, 2); // 16-bit integer converts to two bytes: 65, 65; which in turn is 'AA'
echo string2int('AA'); //back the other way
?>

<< Back to user notes page

To Top