Home  >  Article  >  Backend Development  >  Convert to binary. Reading in the data piece gives zero results

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

WBOY
WBOYforward
2024-02-08 22:06:09562browse

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)

Running this code gives

[1 0 2 0 3 0]
got: []

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:")
}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete