Convert string to binary in Go

huangapple go评论146阅读模式
英文:

Convert string to binary in Go

问题

在Go语言中,将字符串转换为二进制表示的方法如下:

package main

import (
	"fmt"
	"strconv"
)

func stringToBinary(str string) string {
	binary := ""
	for _, char := range str {
		binary += fmt.Sprintf("%08b", char)
	}
	return binary
}

func main() {
	str := "A"
	binary := stringToBinary(str)
	fmt.Println(binary)
}

这段代码中,我们定义了一个stringToBinary函数,它接受一个字符串作为参数,并返回该字符串的二进制表示。在函数内部,我们使用一个循环遍历字符串中的每个字符,然后使用fmt.Sprintf将每个字符转换为8位的二进制表示,并将结果拼接到binary字符串中。最后,我们在main函数中调用stringToBinary函数,并打印结果。

对于输入字符串"A",输出结果将是"01000001"。这段代码可以处理任意长度的字符串,并将其转换为对应的二进制表示。

英文:

How do you convert a string to its binary representation in Go?

Example:

> Input: "A"
>
> Output: "01000001"

In my testing, fmt.Sprintf("%b", 75) only works on integers.

答案1

得分: 6

将1个字符的字符串转换为字节,以获取其数值表示。

s := "A"
st := fmt.Sprintf("%08b", byte(s[0]))
fmt.Println(st)

输出结果:"01000001"

(请注意,代码中的"%b"(中间没有数字)会导致输出中的前导零被删除。)

英文:

Cast the 1-character string to a byte in order to get its numerical representation.

s := "A"
st := fmt.Sprintf("%08b", byte(s[0]))
fmt.Println(st)

Output:  "01000001"

(Bear in mind code "%b" (without number in between) causes leading zeros in output to be dropped.)

答案2

得分: 5

你必须迭代字符串的符文:

func toBinaryRunes(s string) string {
    var buffer bytes.Buffer
    for _, runeValue := range s {
        fmt.Fprintf(&buffer, "%b", runeValue)
    }
    return fmt.Sprintf("%s", buffer.Bytes())
}

或者迭代字节:

func toBinaryBytes(s string) string {
    var buffer bytes.Buffer
    for i := 0; i < len(s); i++ {
        fmt.Fprintf(&buffer, "%b", s[i])
    }
    return fmt.Sprintf("%s", buffer.Bytes())
}

在线演示:

http://play.golang.org/p/MXZ1Y17xWa

英文:

You have to iterate over the runes of the string:

func toBinaryRunes(s string) string {
	var buffer bytes.Buffer
	for _, runeValue := range s {
		fmt.Fprintf(&amp;buffer, &quot;%b&quot;, runeValue)
	}
	return fmt.Sprintf(&quot;%s&quot;, buffer.Bytes())
}

Or over the bytes:

func toBinaryBytes(s string) string {
	var buffer bytes.Buffer
	for i := 0; i &lt; len(s); i++ {
		fmt.Fprintf(&amp;buffer, &quot;%b&quot;, s[i])
	}
	return fmt.Sprintf(&quot;%s&quot;, buffer.Bytes())
}

Live playground:

http://play.golang.org/p/MXZ1Y17xWa

huangapple
  • 本文由 发表于 2015年9月21日 08:20:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/32685687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定