5

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 ?

6
  • 3
    so what's the background that you don't want to use strconv ?
    – ymonad
    Commented Feb 2, 2017 at 8:04
  • 1
    of course you can do something like this: Go Playground, but I don't this this is what you want.
    – ymonad
    Commented Feb 2, 2017 at 8:11
  • I used strconv at first, but after studying task i found out that the requirements were not to use this package
    – Elmor
    Commented Feb 2, 2017 at 8:58
  • and i dont't want to end up with bunch of if else like golang.org/src/strconv/itoa.go?s=628:668#L60
    – Elmor
    Commented Feb 2, 2017 at 9:00
  • 1
    The radix is only relevant to the string representation, so why not use strconv to do it? Otherwise you are just going to be implementing the functions from strconv yourself. (BTW, did you read the source if itoa.go? The if else chain, which isn't very long at 3 blocks, is only there for optimizations.)
    – JimB
    Commented Feb 2, 2017 at 20:54

4 Answers 4

9
package main

import (
    "fmt"
    "math/big"
)

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

Demo

3

Use the math package and a log identify:

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

2

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.

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.