PHP實現UCS2編碼解碼
//手機發送簡訊時編碼
/***
* @Method Ucs2Code UCS2編碼
* @Param $str 輸入字串
* @Param $encod 輸入字串編碼型別(UTF-8,GB2312,GBK)
* @Return 返回編碼後的字串
*/
function Ucs2Code($str,$encode="UTF-8"){
$jumpbit=strtoupper($encode)=='GB2312'?2:3;//跳轉位數
$strlen=strlen($str);//字串長度
$pos=0;//位置
$buffer=array();
for($pos=0;$pos<$strlen;){
if(ord(substr($str,$pos,1))>=0xa1){//0xa1(161)漢字編碼開始
$tmpChar=substr($str,$pos,$jumpbit);
$pos+=$jumpbit;
}else{
$tmpChar=substr($str,$pos,1);
++$pos;
}
$buffer[]=bin2hex(iconv("UTF-8","UCS-2",$tmpChar));
}
return strtoupper(join("",$buffer));
}
/***
* @Method unUcs2Code UCS2解碼
* @Param $str 輸入字串
* @Param $encod 輸入字串編碼型別(UTF-8,GB2312,GBK)
* @Return 返回解碼後的字串
*/
function unUcs2Code($str,$encode="UTF-8"){
$strlen=strlen($str);
$step=4;
$buffer=array();
for($i=0;$i<$strlen;$i+=$step){
$buffer[]=iconv("UCS-2",$encode,pack("H4",substr($str,$i,$step)));
}
return join("",$buffer);
}
echo Ucs2Code("進入圍欄");
echo unUcs2Code("8FDB516556F4680F");