二进制字符串转换为Unicode

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

Binary string to unicode

问题

我不确定为什么我的二进制字符串转Unicode的函数不起作用...有人能指出问题或帮我修复吗?我将二进制字符串分块的原因是它太大了,ParseInt无法处理。请参考下面的playground链接查看示例。

func binToString(s []byte) string {
    var counter int
    chunk := make([]byte, 7)
    var buf bytes.Buffer
    for i := range s {
        if i%8 == 0 {
            counter = 0
            if i, err := strconv.ParseInt(string(chunk), 2, 64); err == nil {
                buf.WriteString(string(i))
            }
        } else {
            chunk[counter] = s[i] //我知道我可以在这里使用取模运算,但我正在测试,使用计数器更容易跟踪和测试
            counter++
        }
    }
    return buf.String()
}

转换时,它似乎要么漏掉一个字符,要么添加一个字符(或两个字符)。

这是一个playground链接,展示了函数不按预期工作的示例。

playground链接

英文:

I'm not 100% sure why my binary string to unicode isn't working..can anyone point out the issue or help me patch it? Also the reason why i chunk out the binary is that it is too large for ParseInt to handle. See the playground link below for an example.

func binToString(s []byte) string {
	var counter int
	chunk := make([]byte, 7)
	var buf bytes.Buffer
	for i := range s {
		if i%8 == 0 {
			counter = 0
			if i, err := strconv.ParseInt(string(chunk), 2, 64); err == nil {
				buf.WriteString(string(i))
			}
		} else {
			chunk
0
+
网站访问量
= s[i] //i know i can use modulus here too but i was testing and an counter was easier to track and test for me counter++ } } return buf.String() }

It either seems to miss a character or add an character (or two) on conversion.

Here is a playground link showing an example of the function not working as expected.

答案1

得分: 1

你的函数可以以更简单、更高效的方式实现:

func binToString(s []byte) string {
    output := make([]byte, len(s)/8)
    for i := 0; i < len(output); i++ {
        val, err := strconv.ParseInt(string(s[i*8:(i+1)*8]), 2, 64)
        if err == nil {
            output[i] = byte(val)
        }
    }
    return string(output)
}

链接:https://play.golang.org/p/Fmo7I-rN3c

英文:

Your function could be implemented in a simpler, more efficient manner:

func binToString(s []byte) string {
	output := make([]byte, len(s)/8)
	for i := 0; i &lt; len(output); i++ {
		val, err := strconv.ParseInt(string(s[i*8:(i+1)*8]), 2, 64)
		if err == nil {
			output[i] = byte(val)
		}
	}
	return string(output)
}

https://play.golang.org/p/Fmo7I-rN3c

huangapple
  • 本文由 发表于 2017年6月9日 06:11:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/44446371.html
匿名

发表评论

匿名网友

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

确定