2014-10-03 124 views
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]); 
} 

回答

2

這其實就這麼簡單

$str = pack('N', $int); 

看到pack。和反向:

$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); 
} 

基本上,每一次轉向8位,使用0xFF面膜(= 255 )去除高位。

+0

男人,這是完美的!哈哈,我現在感覺很傻!我會在讓我接受這個答案的時候。 – donatJ 2014-10-03 19:00:57