小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Go語言實(shí)現(xiàn)Base64、Base58編碼與解碼

 菌心說 2021-09-25

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

}

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多