Home > Enterprise >  RESOLVED - Golang - slice strings address to bytes
RESOLVED - Golang - slice strings address to bytes

Time:11-14

I'm trying to convert this javascript code into Golang with no success.

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=

My code in golang, but it doesn't generate the same result

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))
    }

Can you help me?

CodePudding user response:

Resolved!

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)
            ele, e := hex.DecodeString(v)
            if e != nil {
                return ""
            }
            value = value   string(ele)
        }
        return base64.StdEncoding.EncodeToString([]byte(value))
    }
    ```

CodePudding user response:

Use the encoding/hex DecodeString function as suggested by rustyx in a comment:

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

Run on the playground.

Use this code to ignore whitespace in the hex string:

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
}
  • Related