<p>Hello Guys,</p>
<p>do you know a way to parse a binary string into a readable string?
Example:
"01010100 01100101 01110011 01110100" into "Test"</p>
<hr/>**评论:**<br/><br/>popillol: <pre><p>Not sure if this can be shortened, but <a href="https://play.golang.org/p/0PLBonPTm9u" rel="nofollow">here's an option</a></p>
<pre><code>package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
input := "01010100 01100101 01110011 01110100"
b := make([]byte, 0)
for _, s := range strings.Fields(input) {
n, _ := strconv.ParseUint(s, 2, 8)
b = append(b, byte(n))
}
fmt.Println(string(b))
}
</code></pre></pre>aNNdii: <pre><p>Thank you, had the same approach. I thought there is a native functions to do this kind of things. :-) </p>
<p><a href="https://play.golang.org/p/V1JPZ1zI8Pb" rel="nofollow">Here is my solution, based on yours.</a></p>
<pre><code>package main
import (
"fmt"
"regexp"
"strconv"
)
func main() {
input := "01010100011001010111001101110100"
r, _ := regexp.Compile("[0|1]{8}")
match := r.FindAllString(input, -1)
b := make([]byte, 0)
for _, s := range match {
n, _ := strconv.ParseUint(s, 2, 8)
b = append(b, byte(n))
}
fmt.Println(string(b))
}
</code></pre></pre>templarrei: <pre><p>A slightly revised (optimised) version would be: <a href="https://play.golang.org/p/tRQP9WnOe40" rel="nofollow">https://play.golang.org/p/tRQP9WnOe40</a></p>
<p>EDIT: Updated the link to drop my own experiments :D</p></pre>TUSF: <pre><p>Just letting you know, but:</p>
<blockquote>
<p>prog.go:12:7: t declared and not used</p>
</blockquote></pre>templarrei: <pre><p>Thanks, mate, dropped :D</p></pre>robpike: <pre><p>This is one of the few occasions when Scanf (actually Sscanf) is worthwhile. <a href="https://play.golang.org/p/EhhBfcaqA9b" rel="nofollow">https://play.golang.org/p/EhhBfcaqA9b</a></p></pre>nikajon_es: <pre><p>You can also use the big number library. Which may be more memory, but easier to follow.</p>
<pre><code>func main() {
i := new(big.Int)
i.SetString("0b01010100011001010111001101110100", 0) // inferred
fmt.Println(string(i.Bytes()))
}
</code></pre>
<p><a href="https://play.golang.org/p/wUWbCJ556A1" rel="nofollow">https://play.golang.org/p/wUWbCJ556A1</a></p></pre>claudiodcsilva: <pre><p>And for least clear code of the day:</p>
<pre><code>package main
import (
"fmt"
)
func main() {
input := "01010100011001010111001101110100"
b := []byte(input)
a := make([]byte, (len(b)/8)+ len(b)%8 - int(uint(len(b)%8 - 1)))
for i := 0; i < len(b); i++ {
a[i/8] |= ((b[i] - 48) << uint(7-i%8))
}
fmt.Println(string(a))
}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传