golang实现base62编码

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))
}

相关文章

程序目录结构 简单实现,用户登录后返回一个jwt的token,下次请求带上token请求用户信息接口并返回信息...
本篇博客的主要内容是用go写一个简单的Proof-of-Work共识机制,不涉及到网络通信环节,只是一个本地的简...
简介 默克尔树(MerkleTree)是一种典型的二叉树结构,其主要特点为: 最下面的叶节点包含存储数据或其...
接下来学习并发编程, 并发编程是go语言最有特色的地方, go对并发编程是原生支持. goroutine是go中最近本...
先普及一下, 什么是广度优先搜索 广度优先搜索类似于树的层次遍历。从图中的某一顶点出发,遍历每一个顶...
第一天: 接口的定义和实现 第二天: 一. go语言是面向接口编程. 在学习继承的时候说过, go语言只有封装,...