二进制字符串到十六进制

I have a string with 128 values like 011100010.... I would like to convert this to a hex string. What I found was the other direction:

func partHexToBin(s string) string {
    ui, err := strconv.ParseUint(s, 16, 8)
    if err != nil {
        return ""
    }

    return fmt.Sprintf("%016b", ui)
}

You can do the exact same thing the other way, since ParseInt allows you to pass the base of the number (decimal, hexadecimal, binary, etc.)

ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

Then, once you changed the base in the ParseUint call from 16 to 2, you'll need to change your Sprintf call to print the number to hexadecimal, using the %x format flag.

Please note however that using ParseUint followed by a call to Sprintf might not be the most performant solution.

See this example:

package main

import (
    "fmt"
    "strconv"
)

func parseBinToHex(s string) string {
    ui, err := strconv.ParseUint(s, 2, 64)
    if err != nil {
        return "error"
    }

    return fmt.Sprintf("%x", ui)
}

func main() {
    fmt.Println(parseBinToHex("11101"))
}

Output gives

1d

Feel free to play around with it on the Playground