Golang 之 Base62 编码

qufo · · 3481 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Base62 编码用62个可见字符来编码信息,也就是所谓的62进制,可用于缩短地址之类的。实现起来也很简单。当然,这个实现跟别人家的有可能不一样,反正自己能编能解就行。 

package main

import (
    "math"
    "strings"
)

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

/**
 * 编码 整数 为 base62 字符串
 */
func Encode(number int) string {
    if number == 0 {
        return "0"
    }
    result := make([]byte , 0)
    for number > 0 {
        round  := number / CODE_LENTH
        remain := number % CODE_LENTH
        result = append(result,CODE62[remain])
        number  = round
    }
    return string(result)
}


/**
 * 解码字符串为整数
 */
func Decode(str string) int {
    str = strings.TrimSpace(str)
    var result int = 0
    for index,char := range []byte(str){
        result +=  EDOC[string(char)] * int(math.Pow(CODE_LENTH,float64(index)))
    }
    return result
}

 

里面硬编码了 CODE_LENGTH 是不想每次去算一下长度,省点时间。

 


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:qufo

查看原文:Golang 之 Base62 编码

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3481 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传