Reputation: 615
In golang, how can I convert a string to binary string? Example: 'CC' becomes 10000111000011
Upvotes: 11
Views: 26048
Reputation: 3228
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.
Upvotes: 21
Reputation: 156
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
}
Upvotes: 3
Reputation: 12246
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".
Upvotes: 6