dongtiao2976 2019-05-23 05:04
浏览 302
已采纳

如何生成随机的Uint32 Go

I need to generate random Uint32 type, I know how to do in int but because of high numbers cause an overflow.

is it possible to generate random Uint32 in min and max range?

  • 写回答

1条回答 默认 最新

  • douou8954 2019-05-23 05:09
    关注

    You can just call the standard library:

    https://golang.org/pkg/math/rand/#Uint32

    To force it within a range, you can use modulu and plus

    Example:

    func randU32(min, max uint32) uint32 {
        var a = rand.Uint32()
        a %= (max - min)
        a += min
        return a
    }
    

    on playground:

    https://play.golang.org/p/AlMfjJOTvtv

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?