osnosn

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

linux_shell_生成随机整数_random

转载注明来源: 本文链接 来自osnosn的博客,写于 2021-09-18.

参考

方法

  • rand=$(shuf -i 1-999 -n1)
    • 这个比较好。速度和 od 差不多。
  • rand=$(head -c6 /dev/urandom|sum |cut -f1 -d' '|sed -e 's/^0*//')
  • rand=$(head -c2 /dev/urandom |od -A n -t u2)
  • od -A n -t u2 -N2 /dev/urandom|tr -d ' '
  • rand=$(od -A n -t u2 -N2 /dev/urandom)
    • 这个比较好。速度和 shuf 差不多。
  • rand=$RANDOM
    • 速度最快,可是仅 bash 可用
  • rand=$(tr -cd "[:digit:]" < /dev/urandom | head -c 6|sed -e 's/^0*//')
  • rand=$(tr -cd 0-9 < /dev/urandom | head -c 6|sed -e 's/^0*//')
  • rand=$(date +%s%N)
  • openssl rand -hex 10
    • 输出 hex 格式
  • rand=$(date +%N|awk '{srand($1); printf "%d",rand()*1000000}')

Openwrt lua 随机数

function random_seed()
    local in_file = io.open("/dev/urandom", "rb")
    if in_file ~= nil then
        local d= in_file:read(4)
        sd=d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536)  + (d:byte(4)/2 * 65536 * 256)
        math.randomseed(sd)
        in_file:close()
    else
        math.randomseed(tostring(os.time()):reverse():sub(1, 7))
    end
end

aa=random_seed()
for i=1,5 do
  print(math.random(8,12 ),math.random(13,20),math.random(0,5),math.random(0,5))
end
local fs=require "nixio.fs"
function rand1(min,max)   -- max<256
   local rand=fs.readfile('/dev/urandom', 1)
   rand=rand:byte(1)
   rand=rand/256*(max-min)+min
   return math.floor(rand+0.5)
end
local randnum=rand1(8,12)

local rand=fs.readfile('/dev/urandom', 2)
rand=math.randomseed(rand:byte(1)+rand:byte(2)*256)
local randnum=math.random(8,12)

转载注明来源: 本文链接 https://www.cnblogs.com/osnosn/p/15308304.html
来自 osnosn的博客 https://www.cnblogs.com/osnosn/ .


posted on 2021-09-18 13:42  osnosn  阅读(225)  评论(0编辑  收藏  举报