go语言 base58编码解码

痞子三分冷 提交于 2020-01-30 00:19:19
package main

import (
    "bytes"
    "encoding/hex"
    "fmt"
    "math/big"
)

var base58Alphabets = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")

func main() {
    // testReverse()

    str := "a"
    _, res := Base58Encode([]byte(str))
    fmt.Println("res=", res)
    resByte, resStr := Base58Decode([]byte(res))
    fmt.Println("resByte=", resByte)
    fmt.Println("resStr=", resStr)

}

// Base58Encode 编码
func Base58Encode(input []byte) ([]byte, string) {
    x := big.NewInt(0).SetBytes(input)
    fmt.Println("x=", x)
    base := big.NewInt(58)
    zero := big.NewInt(0)
    mod := &big.Int{}
    var result []byte
    // 被除数/除数=商……余数
    fmt.Println("开始循环-------")
    for x.Cmp(zero) != 0 {
        x.DivMod(x, base, mod)
        fmt.Println("mod=", mod)
        fmt.Println("x=", x)
        result = append(result, base58Alphabets[mod.Int64()])
        fmt.Println("一次循环结束-------")
    }
    ReverseBytes(result)
    return result, string(result)
}

// Base58Decode 解码
func Base58Decode(input []byte) ([]byte, string) {
    result := big.NewInt(0)
    for _, b := range input {
        charIndex := bytes.IndexByte(base58Alphabets, b)
        result.Mul(result, big.NewInt(58))
        result.Add(result, big.NewInt(int64(charIndex)))
    }
    decoded := result.Bytes()
    if input[0] == base58Alphabets[0] {
        decoded = append([]byte{0x00}, decoded...)
    }
    return decoded, string(decoded)
}

func testReverse() {
    str := "12345678"
    // data := []byte(str)
    data, _ := hex.DecodeString(str)
    fmt.Println(data)
    ReverseBytes(data)
    fmt.Println(fmt.Sprintf("%v", data))
}

// ReverseBytes 翻转字节
func ReverseBytes(data []byte) {
    for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
        data[i], data[j] = data[j], data[i]
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!