Skip to main content
edited title
Link
Kokizzu
  • 235
  • 1
  • 9

Convert int64 to custom base 64base64 number string

Source Link
Kokizzu
  • 235
  • 1
  • 9

Convert int64 to custom base 64 number string

I want to convert int64 to custom base 64 number string, with this specification:

0..9   -> 0..9
10..35 -> a..z
36..61 -> A..Z
62     -> _
63     -> -

Is this implementation correct/efficient?

func EncodeLogKey(id int64) string {
  str := make([]byte,0,12)
  if id == 0 { return "0" }
  for id>0 {
    var ch rune
    mod := rune(id % 64)
    if mod <= 10 {
      ch = '0' + mod
    } else if mod <= 10+26 {
      ch = 'a' + (mod - 10)
    } else if mod <= 10+26+26 {
      ch = 'A' + (mod - 10 - 26)
    } else if mod % 2 == 0 {
      ch = '_'
    } else {
      ch = '-'
    }
    str = append(str,byte(ch))
    id /= 64
  }
  return string(str)
}

func DecodeLogKey(logKey string) (int64, error) {
  res := int64(0)
  for ch := range logKey {
    res *= 64
    mod := int64(ch)
    if ch >= '0' && ch <= '9' {
      res += (mod - '0')
    } else if ch >= 'a' && ch <= 'z' {
      res += 10 + (mod - 'a')
    } else if ch >= 'A' && ch <= 'Z' {
      res += 10 + 26 + (mod - 'A')
    } else if ch == '_' {
      res += 10 + 26 + 26
    } else if ch == '-' {
      res += 10 + 26 + 26 + 1
    } else {
      return res, fmt.Errorf("Invalid logKey character: '%c'", res)
    }
  }
  return res, nil
}