首页 > 解决方案 > Golang - 将字符串地址切片为字节

问题描述

我正在尝试将此 javascript 代码转换为 Golang,但没有成功。

function hexToBase64(value) {
    const xxx = value.replace(/\r|\n/g, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ');
    const xx1 = String.fromCharCode.apply(null,xxx);
    return btoa(xx1);
}

const item = hexToBase64("8953bed713db2113b8e8215b444b7d3e4bca6c139d3d54bb77f8cf7f07ca5482");
console.log(item);

OUTPUT: iVO+1xPbIRO46CFbREt9PkvKbBOdPVS7d/jPfwfKVII=

我在 golang 中的代码,但它不会产生相同的结果

hexToBase64 := func(input string) string {
        x := regexp.MustCompile(`\r|\n`).ReplaceAllString(string(input), "")
        x1 := regexp.MustCompile(`([\da-fA-F]{2}) ?`).ReplaceAllString(x, "0x$1 ")
        x2 := regexp.MustCompile(` +$`).ReplaceAllString(x1, "")
        x3 := strings.Split(x2, " ")
        var value string
        for _, v := range x3 {
            v = strings.Replace(v, "0x", "", -1)
            i, e := strconv.ParseUint(v, 16, 64)
            if e != nil {
                panic(e)
            }
            value = value + string(rune(i))
        }
        return base64.StdEncoding.EncodeToString([]byte(value))
    }

你能帮助我吗?

标签: javascriptnode.jsgoencodingbase64

解决方案


使用rustyx 在评论中建议的encoding/hex DecodeString函数:

func hexToBase64(s string) (string, error) {
    b, err := hex.DecodeString(s)
    return base64.StdEncoding.EncodeToString(b), err
}

在操场上奔跑

使用此代码忽略十六进制字符串中的空格:

var killWS = strings.NewReplacer("\n", "", "\r", "", " ", "", "\t", "")

func hexToBase64(s string) (string, error) {
    b, err := hex.DecodeString(killWS.Replace(s))
    return base64.StdEncoding.EncodeToString(b), err
}

推荐阅读