猿问

在 Go 中将字符串转换为二进制

在 Go 中如何将字符串转换为其二进制表示?

例子:

输入:“A”

输出:“01000001”

在我的测试中,fmt.Sprintf("%b", 75)只适用于整数。


炎炎设计
浏览 686回答 2
2回答

眼眸繁星

将 1 个字符的字符串转换为一个字节以获得其数字表示。s := "A"st := fmt.Sprintf("%08b", byte(s[0]))fmt.Println(st)Output:  "01000001"(请记住代码“%b”(中间没有数字)会导致输出中的前导零被删除。)

GCT1015

您必须遍历字符串的符文:func toBinaryRunes(s string) string {&nbsp; &nbsp; var buffer bytes.Buffer&nbsp; &nbsp; for _, runeValue := range s {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(&buffer, "%b", runeValue)&nbsp; &nbsp; }&nbsp; &nbsp; return fmt.Sprintf("%s", buffer.Bytes())}或超过字节:func toBinaryBytes(s string) string {&nbsp; &nbsp; var buffer bytes.Buffer&nbsp; &nbsp; for i := 0; i < len(s); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(&buffer, "%b", s[i])&nbsp; &nbsp; }&nbsp; &nbsp; return fmt.Sprintf("%s", buffer.Bytes())}现场游乐场:http://play.golang.org/p/MXZ1Y17xWa
随时随地看视频慕课网APP

相关分类

Go
我要回答