go language base58 encoding and decoding

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{}
    varResult [] byte 
    // dividend / divisor = Remainder List ...... 
    fmt.Println ( " start cycle ------- " )
     for x.Cmp (ZERO)! = 0 { 
        x.DivMod (X, Base , MOD ) 
        fmt.Println ( " MOD = " , MOD) 
        fmt.Println ( " X = " , X) 
        Result = the append (Result, base58Alphabets [mod.Int64 ()]) 
        fmt.Println ( " cycle end ---- --- " ) 
    } 
    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]
    }
}

Guess you like

Origin www.cnblogs.com/Mishell/p/12241872.html