Elmor
Elmor

Reputation: 4895

Golang number base conversion

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 ?

Upvotes: 5

Views: 11376

Answers (4)

Ravi
Ravi

Reputation: 598

package main

import (
    "fmt"
    "math/big"
)

func main() {
    fmt.Println(big.NewInt(1000000000000).Text(62))
}

Demo

Upvotes: 9

Asdine
Asdine

Reputation: 3046

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

Upvotes: 2

Michael Pettigrew
Michael Pettigrew

Reputation: 111

Use the math package and a log identify:

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

Upvotes: 3

Chris Cherry
Chris Cherry

Reputation: 28574

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.

Upvotes: 2

Related Questions