Convert to binary. Reading in the data piece gives zero results

WBOY
Release: 2024-02-08 22:06:09
forward
585 people have browsed it

Convert to binary. Reading in the data piece gives zero results

In this article, php editor Baicao will introduce how to convert data pieces into binary and give zero results. The process is very simple and you just need to follow a few basic rules. First, the data pieces are read in one by one, and then each data piece is converted into binary. Next, for each binary number, if the digits in it are all zeros, give a zero result. Through this method, we can easily convert the data pieces into binary and get the corresponding results. If you are interested in this process, then follow the editor to learn together!

Question content

I want to read binary data and write it to a file, and my data is just slices. The encoding part is working but my decoding via binary.Read gives zero results. What did i do wrong?

data := []int16{1, 2, 3}
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, data)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    fmt.Println(buf.Bytes())
    // working up to this point

    r := bytes.NewReader(buf.Bytes())
    got := []int16{}
    if err := binary.Read(r, binary.LittleEndian, &got); err != nil {
        fmt.Println("binary.Read failed:")
    }
    fmt.Println("got:", got)
Copy after login

Running this code gives

[1 0 2 0 3 0]
got: []
Copy after login

Playground link here: https://go.dev/play/p/yZOkwXj8BNv

Workaround

You have to make the slice as big as what you want to read from the buffer. You get an empty result because got has a length of zero.

got := make([]int16, buf.Len()/2)
if err := binary.Read(buf, binary.LittleEndian, &got); err != nil {
    fmt.Println("binary.Read failed:")
}
Copy after login

As JimB said, you can read directly from the buffer.

See also the documentation for binary.Read

The above is the detailed content of Convert to binary. Reading in the data piece gives zero results. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!