I want to generate unique random string in a length range. For example, I set length is 10. and every time the generated string is unique .
1条回答 默认 最新
- dtvfxzq3802 2016-07-17 07:10关注
How unique is unique?
if Universally unique, see: https://en.wikipedia.org/wiki/Universally_unique_identifier
Out of a total of 128 bits, Type 4 UUIDs have 6 reserved bits (4 for the version and 2 other reserved bits), so randomly generated UUIDs have 122 random bits.for UUID see: Is there a method to generate a UUID with go language
How to display it? ( Binary-to-text encoding )
A UUID is simply a 128-bit value. if you display it in Hex format it will be 32 character in length.
if you want in 10 place, 128/10=12.8 => 13 bit per place so you need 8192 alphabet !string in Golang encoded in UTF-8 so you may use Unicode alphabet: Unicode has enough code points, see: How many characters can be mapped with Unicode?
conclusion:
if you need Universally unique just use UUIDs.and see: How to generate a random string of a fixed length in golang?
or if you need pseudo random string with length 10, you may use this (but not Universally unique):
package main import "crypto/rand" import "fmt" func main() { n := 5 b := make([]byte, n) if _, err := rand.Read(b); err != nil { panic(err) } s := fmt.Sprintf("%X", b) fmt.Println(s) }
sample output:
FA8EA2FBCE
also see: Output UUID in Go as a short string
解决 无用评论 打赏 举报
悬赏问题
- ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
- ¥85 maple软件,solve求反函数,出现rootof怎么办?
- ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名
- ¥15 maple软件,用solve求反函数出现rootof,怎么办?
- ¥65 汇编语言除法溢出问题
- ¥15 Visual Studio问题
- ¥20 求一个html代码,有偿
- ¥100 关于使用MATLAB中copularnd函数的问题