| package main
 import (
  'bytes'
  'fmt'
  'math/big'
 )
 var base58= []byte('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')
 func Base58Encoding(str string) string {   //Base58編碼
  //1. 轉(zhuǎn)換成ascii碼對(duì)應(yīng)的值
  strByte := []byte(str)
  //fmt.Println(strByte) // 結(jié)果[70 97 110]
  //2. 轉(zhuǎn)換十進(jìn)制
  strTen := big.NewInt(0).SetBytes(strByte)
  //fmt.Println(strTen)  // 結(jié)果4612462
  //3. 取出余數(shù)
  var modSlice []byte
  for strTen.Cmp(big.NewInt(0)) > 0 {
   mod:=big.NewInt(0)     //余數(shù)
   strTen58:=big.NewInt(58)
   strTen.DivMod(strTen,strTen58,mod)  //取余運(yùn)算
   modSlice = append(modSlice, base58[mod.Int64()])    //存儲(chǔ)余數(shù),并將對(duì)應(yīng)值放入其中
   }
  //  處理0就是1的情況 0使用字節(jié)'1'代替
  for _,elem := range strByte{
   if elem!=0{
    break
   }else if elem == 0{
    modSlice = append(modSlice,byte('1'))
   }
  }
  //fmt.Println(modSlice)   //結(jié)果 [12 7 37 23] 但是要進(jìn)行反轉(zhuǎn),因?yàn)榍笥嗟臅r(shí)候是相反的。
  //fmt.Println(string(modSlice))  //結(jié)果D8eQ
  ReverseModSlice:=ReverseByteArr(modSlice)
  //fmt.Println(ReverseModSlice)  //反轉(zhuǎn)[81 101 56 68]
  //fmt.Println(string(ReverseModSlice))  //結(jié)果Qe8D
  return string(ReverseModSlice)
 }
 func ReverseByteArr(bytes []byte) []byte{   //將字節(jié)的數(shù)組反轉(zhuǎn)
  for i:=0; i<len(bytes)/2 ;i++{
   bytes[i],bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i],bytes[i]  //前后交換
  }
  return bytes
 }
 //就是編碼的逆過程
 func Base58Decoding(str string) string { //Base58解碼
  strByte := []byte(str)
  //fmt.Println(strByte)  //[81 101 56 68]
  ret := big.NewInt(0)
  for _,byteElem := range strByte{
   index := bytes.IndexByte(base58,byteElem) //獲取base58對(duì)應(yīng)數(shù)組的下標(biāo)
   ret.Mul(ret,big.NewInt(58))     //相乘回去
   ret.Add(ret,big.NewInt(int64(index)))  //相加
  }
  //fmt.Println(ret)  // 拿到了十進(jìn)制 4612462
  //fmt.Println(ret.Bytes())  //[70 97 110]
  //fmt.Println(string(ret.Bytes()))
  return string(ret.Bytes())
 }
 func main() {
  src := 'Fan'
  res := Base58Encoding(src)
  fmt.Println(res)  //Qe8D
  resD:=Base58Decoding(res)
  fmt.Println(resD)  //Fan
 }
 |