11

In golang, how can I convert a string to binary string? Example: 'CC' becomes 10000111000011

1

3 Answers 3

21

This is a simple way to do it:

func stringToBin(s string) (binString string) {
    for _, c := range s {
        binString = fmt.Sprintf("%s%b",binString, c)
    }
    return 
}

As I included in a comment to another answer you can also use the variant "%s%.8b" which will pad the string with leading zeros if you need or want to represent 8 bits... this will however not make any difference if your character requires greater than 8 bit to represent, such as Greek characters:

Φ 1110100110

λ 1110111011

μ 1110111100

Or these mathematical symbols print 14 bits:

≠ 10001001100000

⊂ 10001010000010

⋅ 10001011000101

So caveat emptor: the example herein is meant as a simple demonstration that fulfills the criteria in the original post, not a robust means for working with base2 representations of Unicode codepoints.

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

Comments

6

First, the binary representation of "CC" is "0100001101000011", you have to take care of leading 0, else your string can be obtained in many different ways.

func binary(s string) string {
    res := ""
    for _, c := range s {
        res = fmt.Sprintf("%s%.8b", res, c)
    }
    return res
}

This produces the desired output: `binary("CC") = "0100001101000011".

2 Comments

+1 but if you want to add the leading 0 it's less code to write res = fmt.Sprintf("%s%.8b", res, c) note the . between % and 8
Thanks, I didn't know about the syntax. And it's probably more efficient too.
3

Another approach

func strToBinary(s string, base int) []byte {

    var b []byte

    for _, c := range s {
        b = strconv.AppendInt(b, int64(c), base)
    }

    return b
}

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.