Golang中rand.Seed()的操作
Posted kumata
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang中rand.Seed()的操作相关的知识,希望对你有一定的参考价值。
记录一下用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 ", mac_adr) //[]string hs_mac := GetMD5Hash(mac_adr[0]) fmt.Printf("hs_mac:%s ",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! ", 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(" rnd:",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()的操作的主要内容,如果未能解决你的问题,请参考以下文章