Golang中rand.Seed()的操作
阿新 • • 發佈:2018-12-21
記錄一下用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(textstring) 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