doujiao7679
2016-05-20 14:16
浏览 816
已采纳

Golang:如何将String转换为二进制表示形式

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

图片转代码服务由CSDN问答提供 功能建议

在golang中,如何将字符串转换为二进制字符串? 示例:“ CC”变为10000111000011

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douzhun8615 2016-05-20 15:42
    已采纳

    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.

    打赏 评论
  • douzhun5971 2016-05-20 16:11

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

    打赏 评论
  • ds0802 2016-05-20 17:02

    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
    }
    
    打赏 评论

相关推荐 更多相似问题