How can I convert from int to hex

前端 未结 6 2035
你的背包
你的背包 2020-12-14 15:53

I want to convert from int to hex in Golang. In strconv, there is a method that converts strings to hex. Is there a similar method to get a hex string from an int?

6条回答
  •  清歌不尽
    2020-12-14 16:45

    Sprintf is more versatile but FormatInt is faster. Choose what is better for you

    func Benchmark_sprintf(b *testing.B) { // 83.8 ns/op
        for n := 0; n < b.N; n++ {
            _ = fmt.Sprintf("%x", n)
        }
    }
    func Benchmark_formatint(b *testing.B) { // 28.5 ns/op
        bn := int64(b.N)
        for n := int64(0); n < bn; n++ {
            _ = strconv.FormatInt(n, 16)
        }
    }
    

提交回复
热议问题