码迷,mamicode.com
首页 > 其他好文 > 详细

Golang中rand.Seed()的操作

时间:2018-12-21 18:43:03      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:printf   地址   byte   err   Golan   ola   nan   get   mat   

记录一下用mac地址+local时间作为seed来产生随机数

package main

import (
    "fmt"
    "math/rand"
    "encoding/binary"
    "time"
    "net"
    "reflect"
    "crypto/md5"
    "encoding/hex"
    "strconv"
    
)

func getMacAddrs() (macAddrs []string) {
    netInterfaces, err := net.Interfaces()
    if err != nil {
        fmt.Printf("fail to get net interfaces: %v", err)
        return macAddrs
    }

    for _, netInterface := range netInterfaces {
        macAddr := netInterface.HardwareAddr.String()
        if len(macAddr) == 0 {
            continue
        }

        macAddrs = append(macAddrs, macAddr)
    }
    return macAddrs
}

func GetMD5Hash(text string) string {
    hasher := md5.New()
    hasher.Write([]byte(text))
    return hex.EncodeToString(hasher.Sum(nil))
}

func main(){
    
    // mac address
    mac_adr := getMacAddrs()
    fmt.Printf("mac addrs: %q\n", mac_adr)  //[]string
    hs_mac := GetMD5Hash(mac_adr[0])
    fmt.Printf("hs_mac:%s\n",hs_mac) // string
    fmt.Println("hs_mac_type:",reflect.TypeOf(hs_mac))

    // 取前16位转换成int64
    newmac, err := strconv.ParseInt(hs_mac[:16], 16, 64)
    if err != nil {
        panic(err)
        fmt.Println("errr")
    }
    fmt.Printf("Hello, %v with type %s!\n", newmac, reflect.TypeOf(newmac))

    i := 0
    for i < 3{                    
        // time (int64)
        t := time.Now().UnixNano() // int64
        fmt.Println("t:",t)
        fmt.Println("t_type:",reflect.TypeOf(t))
        var seed int64 
        seed += t
        seed += newmac
        fmt.Println("seed:",seed)
        rnd := make([]byte,4)
        
        // //UnixNano返回的是int64
        //rand.Seed(time.Now().UnixNano())
        rand.Seed(seed)
        // //fand.Uint32()实现返回一个0-2^32范围内的伪随机数.
        binary.LittleEndian.PutUint32(rnd, rand.Uint32()) 
        fmt.Println("\nrnd:",rnd,"type:",reflect.TypeOf(rnd)) 
        
        i++
    }
}

输出

mac addrs: ["d8:9e:f3:95:25:eb" "fc:01:7c:9e:4c:61"]
hs_mac:4365a5df737a58c3d9ac998937dd4f8f
hs_mac_type: string
Hello, 4856470152322635971 with type int64!
t: 1545388101345983327
t_type: int64
seed: 6401858253668619298

rnd: [255 141 16 39] type: []uint8
t: 1545388101345999732
t_type: int64
seed: 6401858253668635703

rnd: [245 72 11 47] type: []uint8
t: 1545388101346013785
t_type: int64
seed: 6401858253668649756

rnd: [142 160 77 138] type: []uint8

 

Golang中rand.Seed()的操作

标签:printf   地址   byte   err   Golan   ola   nan   get   mat   

原文地址:https://www.cnblogs.com/kumata/p/10157409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!