在Perl中,如何生成由八个十六进制数字组成的随机字符串?

uni*_*n83 8 string random perl activeperl perl5

使用Perl,不使用任何不带ActivePerl的额外模块,如何从0-F创建一个包含8个字符的字符串.例子0F1672DA?填充应该是可控的,最好是8个字符.

我想要生成的字符串种类的更多示例:

28DA9782
55C7128A
Run Code Online (Sandbox Code Playgroud)

Sin*_*nür 16

原则上,你应该能做到

#!/usr/bin/env perl

use strict; use warnings;

for (1 .. 10) {
    printf "%08X\n", rand(0xffffffff);
}
Run Code Online (Sandbox Code Playgroud)

但是,您可能会发现 - 至少在某些具有某些perls(如果不是全部)的系统上 - 范围rand限制为32,768个值.

您还可以研究String :: Random的源代码,以了解如何生成满足其他条件的随机字符串.

但是,我对rand在Windows系统上使用内置功能的警告仍然存在.请参阅Math :: Random :: MT以获得高质量的RNG.

#!/usr/bin/env perl

use strict; use warnings;

my @set = ('0' ..'9', 'A' .. 'F');
my $str = join '' => map $set[rand @set], 1 .. 8;
print "$str\n";
Run Code Online (Sandbox Code Playgroud)

PS:Perl在Windows上的rand问题在5.20中得到修复:

这意味着perl随机数的质量会因平台而异,从Windows上的15位rand()到POSIX平台上的48位,如带有drand48()的Linux.

Perl现在在所有平台上使用自己的内部drand48()实现.这并不能使perl的rand加密安全.[perl#115928]


Ole*_*kov 9

一般示例,允许任何范围的字符:

my @chars = ('0'..'9', 'A'..'F');
my $len = 8;
my $string;
while($len--){ $string .= $chars[rand @chars] };
print "$string\n";
Run Code Online (Sandbox Code Playgroud)


Que*_*tin 6

用于sprintf将数字转换为十六进制。

$foo .= sprintf("%x", rand 16) for 1..8;
Run Code Online (Sandbox Code Playgroud)


Lut*_* L. 5

sprintf("%08X", rand(0xFFFFFFFF))
Run Code Online (Sandbox Code Playgroud)

有些人提到rand的windows-limit与rand的最大值(0x7FFF)或rand(32768)十进制,我会用二进制移位 - 运算符'<<'来克服这个问题.

# overcomes the windows-rand()-only-works-with-max-15bit-(32767)-limitation:
#   needed 8*4==32bit random-number:
#     first get the 15 high-significant bits shift them 17bits to the left,
#     then the next 15bits shifted 2 bits to the left,
#     then the last 2 bits with no shifting:
printf( '%08X', (
    (rand(0x8000)<<17) + (rand(0x8000)<<2) + rand(0b100) )
      );
Run Code Online (Sandbox Code Playgroud)

但我认为这仅仅是学术性的,因为这是一个很难理解的尴尬代码.
我不会在现实代码中使用它,只有速度最重要.
但也许它是最快的解决方案,它正在展示一个模式来克服rand()的限制 - 在windows下的功能......

  • 我的声明有点弱:*至少在某些Windows系统上,`rand`的范围可能限制在32,768个值. (3认同)
  • 为什么不能提交错误报告?:) (2认同)