AS3中Base64的编码和解码都很方便,例如对经过Base64编码后的字符串b64Str,可以用如下方法进行解码:
- private function decodeBin(b64Str:String):Array
- {
- var base64:Base64Decoder;
- var btyArray:ByteArray;
- base64 = new Base64Decoder();
- base64.decode(b64Str);
- btyArray = base64.toByteArray();
- btyArray.endian = Endian.LITTLE_ENDIAN;//Endian.BIG_ENDIAN;
- //下面就可以从ByteArray中读取数据了
- var temp1:int = btyArray.readInt();
- var temp2:float = btyArray.readFloat();
- ……
- ……
- }
当然,上面的参数b64Str里存放的数据有一定的格式(比如是先放一个int,再放一个float……还是先放一个int,再放一个String),不知道数据的格式是无数解码的,至于格式怎么定,完全由你自己来决定。定好数据格式后,你就可以利用Base64来编码,生成上面的b64Str。一般的编码过程如下:
- private function encode():String
- {
- var b64Str:String;
- var base64:Base64Encoder = new Base64Encoder ();
- var btyArray:ByteArray = new ByteArray();
- btyArray.endian = Endian.LITTLE_ENDIAN;//Endian.BIG_ENDIAN;
- //根据自己的数据格式往ByteArray中写数据
- btyArray.writeInt(1);//比如先写一个int
- btyArray.writeFloat(2.9);//再写一个float
- ……
- ……
- ///
- base64.encodeBytes(btyArray);
- b64Str = base64.toString();
- return b64Str;
- }
但有的时候在执行btyArray = base64.toByteArray();时会抛出异常,提示“A partial block (2 of 4 bytes) was dropped. Decoded data is probably truncated!”,这时很有可能是由于binStr中含有空格,而这个空格很可能是字符'+'号转化成的,所以只要把空格还原成"+"即可,代码如下:
- var myPattern:RegExp = //s/gi;
- Str = binStr.replace(myPattern, '+');
如果还是不行,可以考虑用下面的方法:
- private function decodeBin(b64Str:String):Array
- {
- var base64:Base64Decoder;
- var btyArray:ByteArray;
- base64 = new Base64Decoder();
- base64.decode(b64Str);
- try{
- btyArray = base64.toByteArray();
- }catch(e:Error)
- {
- //trace(e.message);
- btyArray = this.myDecode(b64Str);
- }
- btyArray.endian = Endian.LITTLE_ENDIAN;//Endian.BIG_ENDIAN;
- //下面就可以从ByteArray中读取数据了
- var temp1:int = btyArray.readInt();
- var temp2:float = btyArray.readFloat();
- ……
- ……
- }
其中myDecode方法定义如下:
- private function myDecode(binStr:String):ByteArray
- {
- var key:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- var index:int = 0;
- var byteArr1:ByteArray = new ByteArray();
- for (var i:int = 0; i < binStr.length; i = i + 4)
- {
- var tempByte:uint = (key.indexOf(binStr.charAt(i)) & 255) << 18 | (key.indexOf(binStr.charAt(i + 1)) & 255) << 12 | (key.indexOf(binStr.charAt(i + 2)) & 255) << 6 | key.indexOf(binStr.charAt(i + 3)) & 255;
- byteArr1[index++] = (tempByte & 16711680) >> 16;
- byteArr1[index++] = (tempByte & 65280) >> 8;
- byteArr1[index++] = tempByte & 255;
- }
- var byteArr2:ByteArray = new ByteArray(); // end of for
- if (binStr.charCodeAt( -1) == 61)
- byteArr1.readBytes(byteArr2, 0, byteArr1.length - 1);
- else
- byteArr1.readBytes(byteArr2, 0, byteArr1.length - 2);
- return byteArr2;
- }