golang实现base62编码

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

package main

import (
    "fmt"
    "math"
)

var base = []string {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0"}

func base62encode(num int) string {
    baseStr := ""
    for {
        if num <= 0 {
            break
        }

        i := num % 62
        baseStr += base[i]
        num = (num - i) / 62
    }
    return baseStr
}

func base62decode(base62 string) int {
    rs := 0
    len := len(base62)
    f := flip(base)
    for  i := 0; i < len; i++ {
        rs += f[string(base62[i])] * int(math.Pow(62, float64(i)))
    }
    return rs
}

func flip(s []string) map[string]int {
    f := make(map[string]int)
    for index, value := range s {
        f[value] = index
    }
    return f
}

func main() {
    m := base62encode(12645354)
    fmt.Println(m)
    fmt.Println(base62decode(m))
}


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

本文来自:CSDN博客

感谢作者:black_OX

查看原文:golang实现base62编码

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

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