0
我需要将无符号整数转换为4字节的字符串才能在套接字上发送。将Int转换为4字节的PHP字符串
我有以下代码,它的工作原理,但它感觉......恶心。
/**
* @param $int
* @return string
*/
function intToFourByteString($int) {
$four = floor($int/pow(2, 24));
$int = $int - ($four * pow(2, 24));
$three = floor($int/pow(2, 16));
$int = $int - ($three * pow(2, 16));
$two = floor($int/pow(2, 8));
$int = $int - ($two * pow(2, 8));
$one = $int;
return chr($four) . chr($three) . chr($two) . chr($one);
}
我的朋友谁使用了C说,我应该能够bitshifts这样做,但我不知道怎么和他是不是用PHP非常熟悉,是有帮助的。任何帮助,将不胜感激。
要反过来做我已经有了下面的代码
/**
* @param $string
* @return int
*/
function fourByteStringToInt($string) {
if(strlen($string) != 4) {
throw new \InvalidArgumentException('String to parse must be 4 bytes exactly');
}
return (ord($string[0]) << 24) + (ord($string[1]) << 16) + (ord($string[2]) << 8) + ord($string[3]);
}
男人,这是完美的!哈哈,我现在感觉很傻!我会在让我接受这个答案的时候。 – donatJ 2014-10-03 19:00:57