package convx import ( "strings" ) // 说明 // 10进制的数字转换为64进制的字符串,用于生成短链接 // 64进制的字符集,可以自定义 const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/" // DecToBase64 将10进制的数字转换为64进制的字符串 func DecToBase64(n int) string { if n == 0 { return "0" } s := "" for n > 0 { // 取余数,作为64进制的一位 r := n % 64 // 从字符集中找到对应的字符 c := string(base64[r]) // 拼接到结果字符串的前面 s = c + s // 除以64,继续下一轮循环 n = n / 64 } return s } // Base64ToDec 将64进制的字符串转换为10进制的数字 func Base64ToDec(s string) int { n := 0 // 遍历字符串的每个字符 for _, c := range s { // 在字符集中找到字符的索引,作为64进制的一位 i := strings.Index(base64, string(c)) if i == -1 { // 如果字符不在字符集中,返回-1表示错误 return -1 } // 累加到结果数字中,每次乘以64 n = n*64 + i } return n }