3

How do you convert a string to its binary representation in Go?

Example:

Input: "A"

Output: "01000001"

In my testing, fmt.Sprintf("%b", 75) only works on integers.

2 Answers 2

6

Cast the 1-character string to a byte in order to get its numerical representation.

s := "A"
st := fmt.Sprintf("%08b", byte(s[0]))
fmt.Println(st)

Output:  "01000001"

(Bear in mind code "%b" (without number in between) causes leading zeros in output to be dropped.)

Sign up to request clarification or add additional context in comments.

Comments

5

You have to iterate over the runes of the string:

func toBinaryRunes(s string) string {
    var buffer bytes.Buffer
    for _, runeValue := range s {
        fmt.Fprintf(&buffer, "%b", runeValue)
    }
    return fmt.Sprintf("%s", buffer.Bytes())
}

Or over the bytes:

func toBinaryBytes(s string) string {
    var buffer bytes.Buffer
    for i := 0; i < len(s); i++ {
        fmt.Fprintf(&buffer, "%b", s[i])
    }
    return fmt.Sprintf("%s", buffer.Bytes())
}

Live playground:

http://play.golang.org/p/MXZ1Y17xWa

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.