您的位置:首页 > 其它

生成32位的随机十六进制数串

2013-11-04 11:27 274 查看
      前段时间,在做业务的时候需要一个唯一标识码,于是就想到了AS3.0本身提供的一个UIDUtil类,它有一个createUID的静态方法。先来看看API里面的说明:

       

     createUID () 方法

     public static function createUID():String

    语言版本:  ActionScript 3.0

    产品版本:  Flex 3

    运行时版本:  Flash Player 9, AIR 1.1

    基于 ActionScript 的伪随机数生成器和当前时间生成 UID(唯一标识符)。

    UID 的格式为 "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",其中 X 是一个十六进制数字 (0-9, A-F)。

    该 UID 不会是真正全局唯一,但这是在没有播放器支持的情况下生成 UID 的最佳方法。

    返回 String — 新生成的 UID。 

 

public static function createUID():String
{
var uid:Array = new Array(36);
var index:int = 0;

var i:int;
var j:int;

for (i = 0; i < 8; i++)
{
uid[index++] = ALPHA_CHAR_CODES[Math.floor(Math.random() *  16)];
}

for (i = 0; i < 3; i++)
{
uid[index++] = 45; // charCode for "-"

for (j = 0; j < 4; j++)
{
uid[index++] = ALPHA_CHAR_CODES[Math.floor(Math.random() *  16)];
}
}

uid[index++] = 45; // charCode for "-"

var time:Number = new Date().getTime();
// Note: time is the number of milliseconds since 1970,
// which is currently more than one trillion.
// We use the low 8 hex digits of this number in the UID.
// Just in case the system clock has been reset to
// Jan 1-4, 1970 (in which case this number could have only
// 1-7 hex digits), we pad on the left with 7 zeros
// before taking the low digits.
var timeString:String = ( "0000000" + time.toString(16).toUpperCase()).substr(-8);

for (i = 0; i < 8; i++)
{
uid[index++] = timeString.charCodeAt(i);
}

for (i = 0; i < 4; i++)
{
uid[index++] = ALPHA_CHAR_CODES[Math.floor(Math.random() *  16)];
}

return String.fromCharCode.apply( null, uid);
}


 

      在代码的最后一行有一句String.fromCharCode.apply( null, uid);这句的作用类似java里面把StringBuffer转成String,这是对字符串操作效率最高的一种方式了。比如需要在AS里面拼接SQL,这种方式无疑比字符串连接要高的多。

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息