Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a string to a binary file?

Tags:

go

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

how can I do ?

I have tried

    buf := new(bytes.Buffer)

    data := []int8{65, 80}

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

        fp.Write(buf.Bytes())
    }

but I got string 'AP' in file not a binary code

like image 760
karboom Avatar asked Mar 15 '26 09:03

karboom


1 Answers

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

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()
}

which gives:

$ cat out.txt
1000001
1010000
like image 107
topskip Avatar answered Mar 17 '26 21:03

topskip