清风细雨楼 Design By www.eepep.com

前言

最近因为工作的需要,需要写个短链服务,用到了10->62进制,网上找了一个,可以转换最多76位进制的博客,现在分享出来,下面话不多说了,来一起看看详细的介绍吧。

压缩数据用,无损压缩

示例代码:

package main

import (
 "fmt"
 "math"
 "strconv"
 "strings"
)

var tenToAny map[int]string = map[int]string{0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", 16: "g", 17: "h", 18: "i", 19: "j", 20: "k", 21: "l", 22: "m", 23: "n", 24: "o", 25: "p", 26: "q", 27: "r", 28: "s", 29: "t", 30: "u", 31: "v", 32: "w", 33: "x", 34: "y", 35: "z", 36: ":", 37: ";", 38: "<", 39: "=", 40: ">", 41: "", 42: "@", 43: "[", 44: "]", 45: "^", 46: "_", 47: "{", 48: "|", 49: "}", 50: "A", 51: "B", 52: "C", 53: "D", 54: "E", 55: "F", 56: "G", 57: "H", 58: "I", 59: "J", 60: "K", 61: "L", 62: "M", 63: "N", 64: "O", 65: "P", 66: "Q", 67: "R", 68: "S", 69: "T", 70: "U", 71: "V", 72: "W", 73: "X", 74: "Y", 75: "Z"}

func main() {
 fmt.Println(decimalToAny(9999, 76))
 fmt.Println(anyToDecimal("1F[", 76))
}

// 10进制转任意进制
func decimalToAny(num, n int) string {
 new_num_str := ""
 var remainder int
 var remainder_string string
 for num != 0 {
  remainder = num % n
  if 76 > remainder && remainder > 9 {
   remainder_string = tenToAny[remainder]
  } else {
   remainder_string = strconv.Itoa(remainder)
  }
  new_num_str = remainder_string + new_num_str
  num = num / n
 }
 return new_num_str
}

// map根据value找key
func findkey(in string) int {
 result := -1
 for k, v := range tenToAny {
  if in == v {
   result = k
  }
 }
 return result
}

// 任意进制转10进制
func anyToDecimal(num string, n int) int {
 var new_num float64
 new_num = 0.0
 nNum := len(strings.Split(num, "")) - 1
 for _, value := range strings.Split(num, "") {
  tmp := float64(findkey(value))
  if tmp != -1 {
   new_num = new_num + tmp*math.Pow(float64(n), float64(nNum))
   nNum = nNum - 1
  } else {
   break
  }
 }
 return int(new_num)
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

清风细雨楼 Design By www.eepep.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
清风细雨楼 Design By www.eepep.com