douyou7797
2017-02-02 07:50
浏览 86
已采纳

Golang数字基数转换

I was wondering, how do you convert a base10 number from one base to another without usage of strconv in Golang ?

Could you please give me some advice ?

图片转代码服务由CSDN问答提供 功能建议

我想知道,如何在不使用 strconv <的情况下将base10数字从一个基数转换为另一个基数 / code> in Golang吗?

能给我一些建议吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongxian5735 2017-02-03 00:36
    已采纳

    Use the math package and a log identify:

    log_77(x) = log(x) / log(77)

    打赏 评论
  • duancaishi1897 2017-02-02 08:14

    This is probably cheating but I guess you could look at the implementation of strconv.FormatInt, and build some of your own code using that as an example. That way you aren't using it directly, you have implemented it yourself.

    打赏 评论
  • dongtao9095 2018-01-21 01:28

    You can use this function to convert any decimal number to any base with the character set of your choice.

    func encode(nb uint64, buf *bytes.Buffer, base string) {
      l := uint64(len(base))
      if nb/l != 0 {
        encode(nb/l, buf, base)
      }
      buf.WriteByte(base[nb%l])
    }
    
    func decode(enc, base string) uint64 {
      var nb uint64
      lbase := len(base)
      le := len(enc)
      for i := 0; i < le; i++ {
        mult := 1
        for j := 0; j < le-i-1; j++ {
            mult *= lbase
        }
        nb += uint64(strings.IndexByte(base, enc[i]) * mult)
      }
      return nb
    }
    

    You can use it like that:

    // encoding
    var buf bytes.Buffer
    encode(100, &buf, "0123456789abcdef")
    fmt.Println(buf.String())
    // 64
    
    // decoding
    val := decode("64", "0123456789abcdef")
    fmt.Println(val)
    // 100
    
    打赏 评论

相关推荐 更多相似问题