package com.game.common
{
import flash.utils.ByteArray;
import flash.utils.Endian;
public final class GameUnicodeTools
{
private static var ins : GameUnicodeTools;
public static function get instance() : GameUnicodeTools
{
if (!ins)
{
ins = new GameUnicodeTools();
}
return ins;
}
public function GameUnicodeTools():void
{
if( ins )
throw Error("GameUnicodeTools 类被设计成单例!");
}
public function decode( resBytes : ByteArray , len : uint ) : String
{
var bytes : ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
// var surplusLen : uint = ( resBytes.length - resBytes.position + 1 > len ) ? len : resBytes.length - resBytes.position + 1;
var surplusLen : uint = ( resBytes.length - resBytes.position > len ) ? len : resBytes.length - resBytes.position;
bytes.writeBytes( resBytes , resBytes.position , surplusLen );
resBytes.position = resBytes.position + surplusLen - 1;
// bytes.writeByte(0);
// bytes.position = 0;
return this.byArrayToString( bytes );
}
public function encode( resStr : String , len : uint = 0 ):ByteArray
{
return this.StrToByteArray( resStr , ( len > 0 ) ? len : 0 );
}
//unicode string to ByteArray
private function StrToByteArray( strValue : String, uLen:uint = 0 ):ByteArray
{
var byAaryR:ByteArray = new ByteArray();
byAaryR.endian = Endian.LITTLE_ENDIAN;
for ( var i:int = 0; i < strValue.length; ++i )
{
byAaryR.writeShort(strValue.charCodeAt(i));
}
for ( i = 0; i < (uLen - strValue.length); ++i )
{
byAaryR.writeShort(0);
}
return byAaryR;
}
//ByteArray to unicode string
private function byArrayToString( byArray:ByteArray ):String
{
byArray.position = 0;
var strReturn:String = new String();
var strRep:String = "";
// var $cacthBytes : ByteArray = new ByteArray();
// $cacthBytes.endian = Endian.LITTLE_ENDIAN;
var ss : uint = 0;
for(var i:int = 0; i < Math.floor( byArray.length / 2 ) ; i += 1 )
{
// $cacthBytes.clear();
// $cacthBytes.position = 0;
ss = byArray.readShort();
if( ss == 0 )
{
break;
}
else
{
byArray.position -= 2;
if( ss <= 0xff )
{
strRep = byArray.readMultiByte( 1 , "utf-8" );
byArray.position += 1;
}
else
{
strRep = byArray.readMultiByte( 2 , "unicode" );
}
// strReturn = replaceAt(strReturn, strRep, i, i);
strReturn += strRep;
}
}
// var strRep:String = byArray.readMultiByte(byArray.length, "unicode");
return strReturn;
}
private function replaceAt(char:String, value:String, beginIndex:int, endIndex:int):String
{
beginIndex = Math.max(beginIndex, 0);
endIndex = Math.min(endIndex, char.length);
var firstPart:String = char.substr(0, beginIndex);
var secondPart:String = char.substr(endIndex, char.length);
return (firstPart + value + secondPart);
}
}
}
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341