Golang:如何将字符串转换为二进制表示 [英] Golang: How to convert String to binary representation
问题描述
示例:'CC'变为10000111000011
这是一个简单的方法:
func stringToBin(s string)(binString string){
for _,c:= range s {
binString = fmt .Sprintf(%s%b,binString,c)
}
返回
}
正如我在另一个答案的评论中所述,您还可以使用变体%s%.8b
,它将填充字符串零,如果你需要或想要表示8位......然而,如果你的角色需要大于8位来表示,例如希腊字符,这不会有什么区别:
Φ1110100110
<11> 1110111011
<11> 1111111100
或者这些数学符号打印14位:
≠10001001100000
⊂10001010000010
⋅10001011000101
所以要注意的是:这里的例子是一个简单的演示,它满足原始文章中的条件,而不是用于处理Unicode代码点的base2表示的强大工具。
In golang, how can I convert a string to binary string? Example: 'CC' becomes 10000111000011
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.
这篇关于Golang:如何将字符串转换为二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!