AS3 unicode
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);
}
}
}
相关文章