Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: How to convert String to binary representation

Tags:

go

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

like image 635
quangpn88 Avatar asked May 20 '16 14:05

quangpn88


People also ask

How to convert a string into binary?

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

How to convert string to binary array?

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.

How to convert character to binary?

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.


3 Answers

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.

like image 56
Snowman Avatar answered Oct 04 '22 08:10

Snowman


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".

like image 35
T. Claverie Avatar answered Oct 04 '22 09:10

T. Claverie


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
}
like image 28
lhdv Avatar answered Oct 04 '22 07:10

lhdv