How can I write a string to a binary file?

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

How can I write a string to a binary file?

问题

例如,我写的是'A',但在文件中是'1000001',我该怎么办?

我已经尝试了以下代码:

buf := new(bytes.Buffer)
data := []int8{65, 80}

for _, i := range data {
    binary.Write(buf, binary.LittleEndian, i)
    fp.Write(buf.Bytes())
}

但是我在文件中得到的是字符串'AP',而不是二进制代码。

英文:

such as, I write 'A' but in file it is '1000001' ,

how can I do ?

I have tried
<pre>
buf := new(bytes.Buffer)

data := []int8{65, 80}

for _, i := range data {
	binary.Write(buf, binary.LittleEndian, i)
	
    fp.Write(buf.Bytes())
}

</pre>
but I got string 'AP' in file not a binary code

答案1

得分: 1

我没有完全理解你的问题,但也许你想要类似这样的东西:

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	f, err := os.OpenFile("out.txt", os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		log.Fatal(err)
	}
	for _, v := range "AP" {
		fmt.Fprintf(f, "%b\n", v)
	}
	f.Close()
}

这段代码会生成以下输出:

$ cat out.txt
1000001
1010000
英文:

I didn't really understand the question, but perhaps you want something like:

package main

import (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;os&quot;
)

func main() {
	f, err := os.OpenFile(&quot;out.txt&quot;, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		log.Fatal(err)
	}
	for _, v := range &quot;AP&quot; {
		fmt.Fprintf(f, &quot;%b\n&quot;, v)
	}
	f.Close()
}

which gives:

$ cat out.txt
1000001
1010000

huangapple
  • 本文由 发表于 2014年7月16日 15:28:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/24774689.html
匿名

发表评论

匿名网友

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

确定