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

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

In golang, how can I convert a string to binary string? Example: 'CC' becomes 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效