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 如何实验stm32主通道和互补通道独立输出
- ¥30 这是哪个作者做的宝宝起名网站
- ¥60 版本过低apk如何修改可以兼容新的安卓系统
- ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
- ¥50 有数据,怎么建立模型求影响全要素生产率的因素
- ¥50 有数据,怎么用matlab求全要素生产率
- ¥15 TI的insta-spin例程
- ¥15 完成下列问题完成下列问题
- ¥15 C#算法问题, 不知道怎么处理这个数据的转换
- ¥15 YoloV5 第三方库的版本对照问题