我需要将一个无符号整数转换为4字节字符串,以便在套接字上发送。
我有以下代码,它很有效,但感觉。。。令人厌恶的
/**
* @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的朋友说,我应该能够通过比特移位来实现这一点,但我不知道如何实现,而且他对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]);
}
这实际上和一样简单
$str = pack('N', $int);
参见CCD_ 1。反过来:
$int = unpack('N', $str)[1];
如果你想知道如何使用位移进行打包,它是这样的:
function intToFourByteString( $int ) {
return
chr($int >> 24 & 0xFF).
chr($int >> 16 & 0xFF).
chr($int >> 8 & 0xFF).
chr($int >> 0 & 0xFF);
}
基本上,每次移位八位,并用0xFF(=255)掩码以去除高阶位。