user1406177
user1406177

Reputation: 1370

Binary string to hex

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

Upvotes: 2

Views: 6006

Answers (1)

Ullaakut
Ullaakut

Reputation: 3734

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

Upvotes: 4

Related Questions