don*_*atJ 2 php string bit-manipulation
我需要将无符号整数转换为 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);
}
Run Code Online (Sandbox Code Playgroud)
我使用 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]);
}
Run Code Online (Sandbox Code Playgroud)
这实际上很简单
$str = pack('N', $int);
Run Code Online (Sandbox Code Playgroud)
看pack。反之亦然:
$int = unpack('N', $str)[1];
Run Code Online (Sandbox Code Playgroud)
如果您好奇如何使用位移位进行打包,它是这样的:
function intToFourByteString( $int ) {
return
chr($int >> 24 & 0xFF).
chr($int >> 16 & 0xFF).
chr($int >> 8 & 0xFF).
chr($int >> 0 & 0xFF);
}
Run Code Online (Sandbox Code Playgroud)
基本上,每次移位八位并用 0xFF (=255) 进行掩码以删除高位。
| 归档时间: |
|
| 查看次数: |
3737 次 |
| 最近记录: |