12.12.Unicode或ASCII字符之间的转换

问题
我想得到字符的Unicode码或ASCII码。
解决办法
使用String.charCodeAt( )和String.fromCharCode( )方法
讨论
使用fromCharCode( )显示的字符不能直接进入Flash文档,这个方法是静态的,这意味着要通过最顶层的String对象调用它。它接受一个整数或整数序列,然后转为等价的字符,当值小于128时fromCharCode( ) 实际上就是把ASCII码转为字符:
+展开
-ActionScript
/* 显示:
New paragraph: ¶
Cents: ¢
Name: Darron
*/

trace( "New paragraph: " + String.fromCharCode( 182 ) );
trace( "Cents: " + String.fromCharCode( 162 ) );
trace( "Name: " + String.fromCharCode( 68, 97, 114, 114, 111, 110 ) );

charCodeAt( )方法则是把字符转为Unicode编码,如果编码小于128的话,charCodeAt( )就是把字符转为等价的ASCII码:
+展开
-ActionScript
var example:String = "abcd";
//第一个字符a 输出为97
trace( example.charCodeAt( 0 ) );
fromCharCode( )方法还有个用处就是用Unicode 转义符来显示特殊字符:
var example:String = String.fromCharCode( 191 ) + "D"
+ String.fromCharCode( 243 ) + "nde est"
+ String.fromCharCode( 225 ) + " el ba"
+ String.fromCharCode( 241 ) + "o?";
// 测试下第一个字符的编码是否是
// 191.,使用unicode 转义序列来代替fromCharCode( 191 ) ,产生特殊字符,如果是则显示:The
string "¿Dónde está
// el baño?" has a ¿ at the beginning.
if ( example.charCodeAt( 0 ) == 191 ) {
trace( "The string \"" + example + "\" has a \u00BF at the beginning." );
}

使用charCodeAt( )和fromCharCode( )方法可进行字符串的编码和解码处理。

下面的方法创建一个密码文字游戏,但是它仍然是不安全的,不能用于敏感型数据处理。
+展开
-ActionScript
public static function encode( original:String ):String {
// The codeMap property is assigned to the StringUtilities class when the encode( )
// method is first run. Therefore, if no codeMap is yet defined, it needs
// to be created.
if ( codeMap == null ) {
// codeMap 属性是一个关联数组用于映射每个原始编码
codeMap = new Object( );
// 创建编码为0到255的数组
var originalMap:Array = new Array( );
for ( var i:int = 0; i < 256 ; i++ ) {
originalMap.push( i );
}
// 创建一个临时数组用于复制原始编码数组
var tempChars:Array = originalMap.concat( );
// 遍历所有原始编码字符
for ( var i:int = 0; i < originalMap.length; i++ ) {
var randomIndex:int = Math.floor( Math.random( ) * ( tempChars.length - 1 ) );
codeMap[ originalMap[i] ] = tempChars[ randomIndex ];
tempChars.splice( randomIndex, 1 );
}
}
var characters:Array = original.split("");
for ( i = 0; i < characters.length; i++ ) {
characters[i] = String.fromCharCode( codeMap[ characters[i].charCodeAt( 0 ) ] );
}
}
public static function decode( encoded:String ):String {
var characters:Array = encoded.split( "" );
if ( reverseCodeMap == null ) {
reverseCodeMap = new Object( );
for ( var key in codeMap ) {
reverseCodesMap[ codeMap[key] ] = key;
}
}
for ( var i:int = 0; i < characters.length; i++ ) {
characters[i] = String.fromCharCode( reverseCodeMap[ characters[i].charCodeAt( 0 ) ] );
}
return characters.join( "" );
}

下面是具体使用方法:
+展开
-ActionScript
var example:String = "Peter Piper picked a peck of pickled peppers.";
var encoded:String = StringUtilities.encode( example );
// 输出被编码的字符串,因为是随机产生的,每次输出都会不一样:
//
?T#Tmï?~*Tmï*~NcT­ï?ï*TNcï?2ï*~Nc?T­
ï*T**Tm:V
trace( encoded );
// 输出解码后的字符串
// 显示: Peter Piper picked a peck of pickled peppers.
trace( StringUtilities.decode( encoded ) );

加支付宝好友偷能量挖...


评论(0)网络
阅读(96)喜欢(0)flash/flex/fcs/AIR