In golang, how can I convert a string to binary string? Example: 'CC' becomes 10000111000011
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
String class has getBytes() method which can be used to convert String to byte array in Java. getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
To calculate the number value of a binary number, add up the value for each position of all the 1s in the eight character number. The number 01000001, for example, is converted to 64 + 1 or 65.
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.
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".
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With