dongliuzhuan1219
2017-06-08 22:11
浏览 548
已采纳

二进制字符串转换为unicode

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[counter] = 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.

图片转代码服务由CSDN问答提供 功能建议

我不确定100%为什么我的Unicode二进制字符串不起作用..有人可以指出 问题还是帮我打补丁? 另外,我之所以将二进制代码分块,是因为对于ParseInt而言,它太大了。

  func binToString(s [] byte)字符串{
 var counter int 
 chunk:= make([] byte,7  )
 var buf bytes.i的缓冲区
:=范围s {
如果i%8 == 0 {
计数器= 0 
如果i,err:= strconv.ParseInt(string(chunk),2  ,64);  err == nil {
 buf.WriteString(string(i))
} 
} else {
 chunk [counter] = s [i] //我知道我也可以在此处使用模数,但我正在测试和 计数器更容易为我跟踪和测试
计数器++ 
} 
} 
返回buf.String()
} 
   
 
 

在转换时错过一个字符或添加一个(或两个)字符。

这是一个游乐场链接,其中显示了一个 函数未按预期运行的示例。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doumei2023 2017-06-08 22:17
    最佳回答

    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 < 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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题