V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
dyllen

crypto/rand 生成的随机数可以编码成纯数字字符串吗?

  •  
  •   dyllen · Sep 18, 2023 · 1677 views
    This topic created in 964 days ago, the information mentioned may be changed or developed.

    "crypto/rand.Read"生成的随机数可以编码成纯数字字符串吗?有没有现成的官方方法?

    3 replies    2023-09-19 10:25:18 +08:00
    yang0327519
        1
    yang0327519  
       Sep 18, 2023
    package main

    import (
    "crypto/rand"
    "fmt"
    )

    func main() {
    n := 10 // 生成 10 个随机字节
    buf := make([]byte, n)

    _, err := rand.Read(buf)
    if err != nil {
    panic(err)
    }

    result := ""
    for _, b := range buf {
    result += fmt.Sprintf("%03d", b) // 将每个字节转换为三位数字的字符串
    }

    fmt.Println(result) // 输出纯数字字符串
    }
    body007
        2
    body007  
       Sep 19, 2023
    package main

    import (
    "crypto/rand"
    "fmt"
    "math/big"
    )

    func main() {
    err := test()
    if err != nil {
    panic(err)
    }
    }

    func test() error {
    limit := big.NewInt(10000000000) // 指定最大值,[0, max)

    num, err := rand.Int(rand.Reader, limit)
    if err != nil {
    return err
    }

    fmt.Println(num.String())
    return nil
    }
    dyllen
        3
    dyllen  
    OP
       Sep 19, 2023
    @yang0327519
    @body007 都可以,需要可控固定长度。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3038 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 13:35 · PVG 21:35 · LAX 06:35 · JFK 09:35
    ♥ Do have faith in what you're doing.