星期三, 九月 13, 2006

UCS2编码与解码函数,PHP写的

UCS2编码:

UCS2 编码原理,是将单个的字符(1-2 个字节)ISO/IEC10646 的规定,转变为16 Unicode 宽字符。即将单个的字符转换为由四位的'0 '-'9'、'A '-'F'的数字和字 母组成的字符串。待发送的消息以UCS 2 的形式进行发送。

SRC_STR:'ABC1230编码函数 '

DEST_STR:' 00410042004300310032003300307F16780151FD6570'


/**
 *  UCS2解码函数,返回GBK
 */
function UCS2toGB ($msg)
{
    $result = "";
    for ($i=0; $i<strlen($msg); $i+=4)
    {
        $ch1 = substr($msg,$i,2);
        $ch2 = substr($msg,$i+2,2);
        $result .= chr(HexDec($ch2)).chr(HexDec($ch1));
    }
    $result = chr(HexDec("ff")).chr(HexDec("fe")).$result;
    $result = iconv("UTF-16","GBK",$result);
    return $result;
}
/**
 * UCS2编码函数
 */
function GBtoUCS2 ($msg)
{
    $result    = "";
    $msg    = iconv("GBK","UTF-16",$msg);
    for ($i=2; $i<strlen($msg); $i+=2)
    {
        $ch1 = dechex(ord($msg[$i]));
        $ch2 = dechex(ord($msg[$i+1]));
        $ch1 = (strlen($ch1) < 2 ? "0" : "").$ch1;
        $ch2 = (strlen($ch2) < 2 ? "0" : "").$ch2;
        $result    .= $ch2.$ch1;   
    }
    return $result;
}

--
by 无际海

小蚂蚁也有理想--IT蚂蚁工作室
www.ItMaYi.com
www.ItMaYi.cn

没有评论: